/*
 * @Descripttion: 单据公共混入
 * @version: V1.0
 * @Author: GaoWei
 * @Date: 2021-05-13 16:33:13
 * @LastEditors: keyi 5284153+zzz_hc@user.noreply.gitee.com
 * @LastEditTime: 2023-03-06 16:34:43
 */

import { mapState } from "vuex";
//import { pageList } from "@/api/inventory/unit";//计量单位

import { confirm } from '@/api/inventory/inout'


import { list as listDesign } from "@/api/erp/voucherDesign";//动态表单

import { IdFieldToNameField } from "@/utils/customize"

import { getbyid ,released} from '@/api/purchase/voucherDesign';

import { handleDynamicData } from "@/utils/tool/dynamic-data"

import { drawerBox } from "@/components/PopUpLayer";//搜索选择弹窗

import getDate from "@/utils/tool/date";

import { getNowQuantity } from '@/api/inventory/inout';//根据 物料ID 和 仓库ID 获取现存量

import EditableCell from "@/components/OrderDynamicForm/EditableCell";
import OrderDynamicForm from '@/components/OrderDynamicForm/OrderDynamicForm';
import dynamicList from '@/components/OrderDynamicForm/dynamicList';
import dynamicListDetails from '@/components/OrderDynamicForm/dynamicListDetails'
import { numberFormat } from "@/utils/tool/number-formart";
import { Controlwidth } from "@/utils/antTableComponents";
import { _ } from "core-js";
import { getList, detail } from "@/api/finance/financeTemplate";//财务获取凭证模板
import printModal from "@/components/PopUpLayer/printModal"
import btnsWrapper from '@/components/OrderDynamicForm/btnsWrapper'
import MiddleUtils from '@/utils/middle-utils';
import { deepCopy } from "@/utils/tool/object";
import { deleteMainCommonFild } from "@/utils/voucherUtils";

export default {
    components: {
        EditableCell,
        OrderDynamicForm,   //动态表单
        drawerBox,          //抽屉搜索列表
        dynamicList,        //表单列表
        dynamicListDetails, //明细列表
        btnsWrapper,        //顶部按钮
        printModal,         //打印设计页
    },
    updated() {
        Controlwidth("bills_tb", 50);
    },
    data() {
        //销售类型 单据
        let saleVoucherArr = ["SaleQuotation", "SaleOrder", "SaleDelivery", "SaleInvoice", "SaleDispatchVoucher", "ProductionOrder", "ProductionFinish", "ProductionWork", "ProductionPlan", "productionDemand" ,"DelegateProductionWork", "DelegateArrival", "DelegateInvoice"];
        return {
            saleVoucherArr,
            //----------↓样式----------
            btn_grid: {
                xs: 2,
                sm: 2,
                md: 2,
                lg: 2,
                xl: 2
            },
            numbers:1,//liulang new
            formLayout: "inline",
            labelCol: { span: 8 },
            wrapperCol: { span: 16 },
            //----------↑样式----------
            routePath: this.$route.path,
            unitData: [],           //单计量数组
            unitsDataDetails: [],   //多计量数组详细计量

            form: "",
            dynamicFormData: [],
            dynamicFormDataMap: new Map(),
            columns: [],            //明细table的columns
            dataSource: [],         //明细table的数据
            dataSourceNumber: 8,    //明细table初始多少条
            count: 0,               //明细table列表行条数
            slotArray: [],          //明细中 需要编辑的字段

            orderHeaderData: [],    //表头动态表单名
            orderFooterData: [],    //表尾动态表单名
            orderDetailData: [],    //明细动态表单名
            orderDetailBomData: [], //物料明细

            receiptNumber: 0,       //单据编号

            visible: false,         //控制右键菜单显示
            top: 0,
            left: 0,
            thisClickLeftId: 0,      //鼠标左键点击表格的下标
            customClick: (record, index) => ({
                on: {
                    contextmenu: (e) => {//右键事件
                        e.preventDefault();
                        if (record.number != "合计") {
                            this.openMenu(e);
                            //console.log('右键点击的', index, e);
                            this.thisClickId = index;
                            this.thisClickRecord = record;
                        }
                    },
                    click: () => {
                        this.thisClickLeftId = index;//点击行的下标
                        if (this.$route.path == '/production/productionWork' || this.$route.path == '/outsource/outProductionWork') {
                            //加工单和委外加工单
                            this.classWorkCurrent = index;//加工单当前点击
                            this.currentBomId = record.bomId;
                            if (this.showBomDetails) {
                                //获取物料明细
                                this.showBomDetails(record);
                            }
                            if (this.showDetailsRoute) {
                                //获取工序明细
                                this.showDetailsRoute(record);
                            }
                        }
                    }
                },
            }),
            currentBomId: 0,         //加工单当前点击的行的bomId
            classWorkCurrent: 0,    //加工单当前点击的行数
            thisClickId: 0,         //当前右键点击的行的key
            thisClickRecord: {},    //当前右键点击的行的数据

            isRouterAlive: true,

            editData: [],            //修改数据
            orderId: '',              //当前单据id

            unitsAssistSelect: [],   //辅助计量下来数组
            onFillData: [],           //必填字段集合

            editMask: true,     //修改遮罩
            isSaveRun: true,    //保存防连点
            loading: false,     //加载中遮罩层
            voucherState: -1,     //当前单据审核状态
            closedState: 1,     //当前单据打开关闭状态 0关闭 1打开

            enableState: null,    //启用、停用状态


            sourceVoucherData: {},   //数据来源
            sourceVoucherDetails: [], //明细中添加数据来源id
            businessType: null,           //业务类型

            showModel: 'order',      //订单显示模式
            stylePrint: '<style type="text/css" media="print">\n' + '  @page { size: landscape;}\n' + '</style>',
            createUserId: null,      //单据创建人

            // tableScrollLeft: 0,       //table滚动条距离左边的距离


            recordInvoiceType: null,     //记录选中的 发票类型
            isSource: false,//是否有来源单标识
            existingQuantityBack: {},//现存量对象
            newWarehouseId: null,//当前仓库id
            disableEditClumns: null,               // 二次筛选 明细不可编辑字段
            //基础 查询条件（列表 + 翻页）
            basePostData: {
                someBusinessType: '0',    // 指定业务类型 默认 0
            },
            dict: [],//字典
            printVisible: false,//打印设计弹窗
            incomingPrintData: {

            },//传入打印子组件数据

            refreshSearch: true,//用于（财务）往来单位组件更换
            orderData: {},//当前获取的单据数据

            inOutWarning: false,//出入库预警弹窗
            inOutType: null,

            //-------------------------财务凭证模板-------------------
            templateFinanceData: [],//凭证模板数据
            templateVisible: false,
            templateColumns: [{
                title: "模板编号",
                dataIndex: "code",
                key: "code",
                width: 120,
            },
            {
                title: "模板名称",
                dataIndex: "name",
                key: "name",
                width: 120,
            },
            {
                title: "凭证字",
                dataIndex: "word",
                key: "word",
                width: 120,
            },
            {
                title: "描述",
                dataIndex: "remarks",
                key: "remarks",
                width: 120,
            },
            {
                title: "单据类型",
                dataIndex: "voucherTypeName",
                key: "voucherTypeName",
                width: 120,
            },
            {
                title: "来源单据类型",
                dataIndex: "sourceVoucherType",
                key: "sourceVoucherType",
                width: 120,
            },
            {
                title: "状态",
                dataIndex: "status",
                key: "status",
                width: 60,
                customRender: (text, row, index) => {
                    return text == 0 ? '启用' : text == 1 ? '禁用' : '';
                }
            }, {
                title: "是否默认",
                dataIndex: "isDefault",
                key: "isDefault",
                width: 60,
                customRender: (text, row, index) => {
                    return text == 0 ? '否' : text == 1 ? '是' : '';
                }
            }, {
                title: "是否系统",
                dataIndex: "isSys",
                key: "isSys",
                width: 60,
                customRender: (text, row, index) => {
                    return text == 0 ? '否' : text == 1 ? '是' : '';
                }
            }],
            selectedTemplateKeys: [],
            selectedTemplateRows: [],
            columnsModal: [{
                title: "科目来源",
                dataIndex: "accountingType",
                width: 80,
                align: 'left',
                customRender: (value) => {
                    return value == 1 ? '单据上的科目' : value == 2 ? '凭证模版' : ''
                }
            }, {
                title: "科目名称",
                dataIndex: "accountingName",
                width: 80,
                align: 'left',
            }, {
                title: "科目编码",
                dataIndex: "accountingCode",
                width: 80,
                align: 'left',
            }, {
                title: "借贷方向",
                dataIndex: "amountDirection",
                width: 80,
                align: 'left',
                customRender: (value) => {
                    return value == 1 ? '借' : value == 2 ? '贷' : ''
                }
            }, {
                title: "金额来源",
                dataIndex: "amountSource",
                width: 80,
                align: 'left',
                customRender: (value) => {
                    return value == 1 ? '金额' : value == 2 ? '税额' : value == 3 ? '价税合计' : ''
                }
            }, {
                title: "摘要",
                dataIndex: "remark",
                width: 80,
                align: 'left',
            }],
            templateDetails: [],
            templateDetailsMain: [],
            customClickTemplate: (record, index) => ({
                on: {
                    click: () => {
                        this.onSelectTemplateChange([record.id], [record]);
                    }
                },
            }),

            record:[],
            //-------------------------财务凭证模板-------------------
        }
    },

    mounted() {
        // let tableScroll = document.getElementById('bills_tb').querySelector('.ant-table-body');
        // tableScroll.scroll(this.tableScrollLeft, 0);
        //获取单据table的高度
        this.numbers= this.$route.query.numbers;
       console.log(this.numbers,this.$route.query.numbers,'33333333334444uuuuuuu')
        if (this.showModel == 'detail') {
            //工序汇报移除了table 不需要获取高度
        } else {
            setTimeout(() => {
                let tableBox = document.getElementById('bills_tb');
                if (tableBox) {
                    let tableHeight = tableBox.getBoundingClientRect().height;
                    let tableMask = document.getElementsByClassName('edit-mask');

                    if (tableMask.length > 0) {
                        tableMask[0].style.height = tableHeight - 50 + 'px';
                        tableMask[0].style.top = 34 + 'px';
                    }
                }
            }, 500)
        }

        let dict = JSON.parse(localStorage.getItem('dict'));
        let map = new Map();
        dict.forEach(item => {
            map.set(item.id, item)
        });
        this.dict = map;//字典
    },
    watch: {
        visible(value) {
            if (value) {
                document.body.addEventListener("click", this.closeMenu);
            } else {
                document.body.removeEventListener("click", this.closeMenu);
            }
        },
        dataSource(value) {
            this.count = value.length;
        },
    },
    activated() {
        //进入页面就请求最新一条数据
        // this.turnThePage(4,'isloading');
        //console.log('进入页面：this.editMask：', this.editMask);
        if (this.editMask || Object.keys(this.invoiceData).length > 0) {
            this.syncOrder();
        }
    },
    computed: {
        dictionary() {
            return this.$store.state.order.dictionary;
        },
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
            invoiceData: state => state.order.invoiceData,  //生单数据
        }),
        voucherTitle: function () {
            const { showModel } = this;
            switch (showModel) {
                case 'order': return this.$route.meta.name;
                case 'list': return this.$route.meta.name + '列表';
                case 'detail': return this.$route.meta.name + '明细';
                default: return this.$route.meta.name + '统计';
            }
        }
    },
    beforeCreate() {
        this.form = this.$form.createForm(this, { name: "order" });
    },
    created() {
        this.getUnitData();
        this.getGrouplist();
    },
    methods: {
        deleteMainCommonFild,
        //获取计量单位（单计量）
        getUnitData() {
            let postData = {
                //查询条件
                current: 1,
                size: 1000,
                unitGroupId: 0
            };
            pageList(postData).then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    const { records, total, current, size } = data;
                    this.unitData = records;
                }
            }).catch(error => { });
        },
        //计量单位组下面的组单位
        getGrouplist() {
            let requestData = {
                current: 1,
                size: 1000,
                unitGroupId: -1
            }
            pageList(requestData).then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    const { records } = data;
                    this.unitsDataDetails = records;
                }
            }).catch(error => { });
        },
        //根据id返回 非主计量的 辅助计量组
        returnGroupUnits(id) {
            let elementId = null;
            let units = [];
            // this.unitsDataDetails.forEach(element => {
            //     if (id == element.id) {
            //         elementId = element.unitGroupId;
            //     }
            // });
            this.unitsDataDetails.forEach(element => {
                if (id == element.unitGroupId) {// && !element.isMainUnit
                    units.push(element);
                }
            });
            return units;
        },
        //强制刷新表格
        reload() {
            this.isRouterAlive = false;
            this.$nextTick(function () {
                this.isRouterAlive = true;
            });
        },
        //初始化表字段
        initForm(type) {
            //已查
            /**
             * type == 1新增
             * type == 2修改
             */

            if (this.$route.path == '/production/management/productionOrder') {
                this.sourceCode = 'RequirementPlan';
            }

            handleDynamicData(this.sourceCode, this.isAreaPay, this.isAreaX).then(res => {
                //this.isAreaPay 是否是 面积计算表 报价
                //this.isAreaX 是否是新西亚项目
                //采购到货 委外到货 销售发货 销售订单     删除业务类型
                //this.$route.path == '/production/management/productionOrder'
                if (this.$route.path == '/production/management/productionOrder' || this.$route.path == '/procurement/purchaseReceipt' || this.$route.path == '/outsource/outReceipt' || this.$route.path == '/sale/saleDelivery' || this.$route.path == '/inventory/bills/saleDelivery' || this.$route.path == '/sale/saleOrder') {
                    res.forEach((element, index) => {
                        if (element.code == 'businessType') {
                            res.splice(index, 1); //删除下标为i的元素
                        }
                    });
                }
                if(type == 1){
                    this.$store.commit('SET_MRP', []);
                }


                this.dynamicFormData = res;
                this.dynamicFormDataMap = new Map();
                this.onFillData = res.filter(item => {
                    return item.onFill === true;
                })
                //表头字段名
                this.orderHeaderData = res.filter(item => {
                    return item.dataTab === '表头';
                });

                //如果是合同变更 塞入 变更理由
                if (this.routePath == '/contract/contractBillsChange' || this.routePath == '/contract/contractBillsRecord') {
                    this.orderHeaderData.push({
                        code: "changeCause",
                        columnType: "文本",
                        name: '变更原因',
                        dataType: 1,
                        onEdit: true,
                        onFill: true,
                        onOff: true,
                        value: '',
                        valueName: '',
                    })
                }


                //删除往来单位组件的val标识
                this.orderHeaderData.forEach(e => {
                    if (e.code == 'partnerId') {
                        if (type == 1) {
                            //新增默认值
                            e.val = 'supplie';
                            this.forceRerender();
                        } else {
                            e.val = '';
                        }
                    }
                });


                //隐藏表头的仓库字段
                if (this.headerInWherehouse) {
                    this.orderHeaderData.forEach(e => {
                        if (e.code == 'warehouseId') {
                            e.onOff = false;
                        }
                    });
                }

                //隐藏表头的客户
                if (this.headerInCrmName) {
                    this.orderHeaderData.forEach(e => {
                        if (e.code == 'crmId') {
                            e.onOff = false;
                        }
                    });
                }
                //隐藏表头供应商字段
                if (this.headerInVendorName) {
                    this.orderHeaderData.forEach(e => {
                        if (e.code == 'vendorId') {
                            e.onOff = false;
                        }
                    });
                }

                //强制去掉  表头  加工产品名称和加工产品编码
                if (this.isHideDetailsProductId) {
                    this.orderHeaderData.forEach(e => {
                        if (e.code == 'productId' || e.code == 'productCode') {
                            e.onOff = false;
                        }
                    });
                }

                //表头业务类型不可修改
                if (this.headerInBusinessType) {
                    this.orderHeaderData.forEach(e => {
                        if (e.code == 'businessType') {
                            e.onEdit = false;
                        }
                    });
                }

                //表尾字段名
                this.orderFooterData = res.filter(item => {
                    return item.dataTab === '表尾';
                })

                //明细
                this.orderDetailData = res.filter(item => {
                    return item.dataTab === '明细';
                })
                //物料明细
                // this.orderDetailBomData = res.filter(item => {
                //     return item.dataTab === '物料明细';
                // })
                // this.columnsBom = this.regroupTableColumns(this.orderDetailBomData);

                // const editCol = (dd) => {
                //     let aaa = dd.filter(res => { return res.onEdit })
                //     let back = [];
                //     aaa.forEach(item => {
                //         back.push(item.code)
                //     });
                //     return back;
                // }
                // let columnsBomTemp = editCol(this.orderDetailBomData)
                // delete columnsBomTemp[0];
                // this.editColumnBom = columnsBomTemp;

                //产品退库 || 委外产品退库 (实收数量 变为 实退数量)
                // if (this.routePath == '/inventory/bills/delegateOuta' || this.routePath == '/inventory/bills/productOut') {
                //     this.orderDetailData.forEach(element => {
                //         if (element.code == 'baseQuantity') {
                //             element.name = '实收数量';
                //         }
                //     });
                // }
                //采购退货 ||  产品退库 || 委外产品退库
                if (this.routePath == '/inventory/bills/purchaseReturn'
                    || this.routePath == '/procurement/purchaseExamineReturn'
                    || this.routePath == '/inventory/bills/productOut'
                    | this.routePath == '/production/management/productOut'
                    || this.routePath == '/inventory/bills/delegateOuta'
                    || this.routePath == '/outsource/delegateOutBack') {
                    this.orderDetailData.forEach(element => {
                        if (element.code == 'baseQuantity') {
                            element.name = '实发数量';
                        }

                        if (element.code == 'orgBaseQuantity') {
                            element.name = '应发数量';
                        }
                    });
                }
                //销售退货 || 生产退料 || 委外退料
                if (this.routePath == '/inventory/bills/saleOutRet'
                    || this.routePath == '/sale/saleOutRet'
                    || this.routePath == '/inventory/bills/materialOutRet'
                    || this.routePath == '/inventory/bills/delegateOutRet') {
                    this.orderDetailData.forEach(element => {
                        if (element.code == 'baseQuantity') {
                            element.name = '实收数量';
                        }

                        if (element.code == 'orgBaseQuantity') {
                            element.name = '应收数量';
                        }
                    });
                }
                // 主生产计划
                if(this.routePath == '/production/productionDemand') {
                    this.orderDetailData.forEach(element => {
                        if (element.code == 'adjustRate') {
                            element.name = '调整比例(%)';
                        }
                    });
                }

                //明细（表格字段名）
                this.columns = this.regroupTableColumns(this.orderDetailData);
                //console.log(this.columns, 'this.columnsthis.columnsthis.columns')
                let { disableEditClumns } = this;
                let newSlotArray = [];
                for (let i = 0; i < this.columns.length; i++) {
                    if (disableEditClumns && disableEditClumns.indexOf(this.columns[i].dataIndex) > 0) continue;
                    if (this.columns[i].dataIndex != "number") {
                        newSlotArray.push(this.columns[i].dataIndex);
                    }
                }
                this.slotArray = newSlotArray;

                //设置表头日期默认值
                this.orderHeaderData.forEach(item => {
                    if (item.columnType == '日期' && item.value == '' && type ==1) {
                        //console.log(item);
                        this.$set(item, 'value', getDate.getCurrentMoment().format('YYYY-MM-DD'))
                    }
                    if (item.columnType == '起止日期' && item.value == '') {
                        this.$set(item, 'value', [])
                    }

                    if(this.routePath == '/procurement/purchaseRequisition'){
                        if(type == 2){
                            if(item.code == "officeId"){
                                this.$nextTick(()=>{
                                    this.$set(item, 'value', this.orderData.officeName)
                                })
                            }
                            if(item.code == "requisitionUserId"){
                                this.$nextTick(()=>{
                                    this.$set(item, 'value', this.orderData.requisitionUserName)
                                })
                            }
                            if (item.code == 'voucherCode' && item.value == '') {
                                this.$set(item, 'value', this.orderData.voucherCode)
                            }
                        }
                    }


                    if(this.routePath != '/production/productionWork' && this.routePath != '/procurement/purchaseRequisition'){
                        if (item.code == 'voucherCode' && item.value == '' && this.orderDat) {
                            this.$set(item, 'value', this.orderData.voucherCode)
                        }
                        if(type == 2){//1新增
                            if (item.code == 'voucherDate' && this.orderDat) {
                                this.$set(item, 'value', this.orderData.voucherDate)
                            }
                        }
                    } else {
                        if (item.name == '单据日期' ) {
                            this.$set(item, 'value', getDate.getCurrentMoment().format('YYYY-MM-DD'))
                        }
                    }
                    if(this.routePath == '/procurement/purchaseReceipt'){
                        if(type == 2){//1新增
                            if(item.code == "voucherDate"){
                                this.$nextTick(()=>{
                                    this.$set(item, 'value', this.orderData.voucherDate)
                                })
                            }
                            if(item.code == "vendorId"){
                                this.$nextTick(()=>{
                                    this.$set(item, 'value', this.orderData.vendorName)
                                })
                            }
                            if(item.code == "voucherCode"){
                                this.$nextTick(()=>{
                                    this.$set(item, 'value', this.receiptNumber != 0 ? this.receiptNumber : '')
                                })
                            }
                        }
                    }

                    if(this.routePath == '/sale/saleOrder'){
                        if(type == 2){//1新增
                            if(item.code == "voucherCode"){
                                this.$nextTick(()=>{
                                    this.$set(item, 'value', this.orderData.voucherCode)
                                })
                            }
                            if(item.code == "crmId"){
                                this.$nextTick(()=>{
                                    this.$set(item, 'value', this.orderData.crmCustomerName ? this.orderData.crmCustomerName : this.orderData.crmName)
                                })
                            }
                            if(item.code == "voucherDate"){
                                this.$nextTick(()=>{
                                    this.$set(item, 'value', this.orderData.voucherDate)
                                })
                            }
                        }
                    }

                })


                if(this.routePath == '/production/productionWork'){
                    this.getCode()
                }


                if(this.$route.query.numbers === 4){
                    this.getCode()
                    this.orderHeaderData.forEach(item => {
                        if (item.name == '单据日期' ) {
                            this.$set(item, 'value', getDate.getCurrentMoment().format('YYYY-MM-DD'))
                        }
                    })
                }

                //设置表尾日期默认值
                this.orderFooterData.forEach(item => {
                    // if (item.columnType == '日期' && item.value == '') {
                    //     this.$set(item, 'value', getDate.getCurrentMoment().format('YYYY-MM-DD'))
                    // }
                    if (item.columnType == '起止日期' && item.value == '') {
                        this.$set(item, 'value', [])
                    }

                    // 生产订单
                    if(this.routePath == '/production/productionWork') {
                        if (item.name == '创建人'  && !item.value) {
                            this.$set(item, 'value', this.$store.state.user.name)
                        }
                        if (item.name == '创建日期'  && !item.value) {
                            this.$set(item, 'value', getDate.getCurrentMoment().format('YYYY-MM-DD'))
                        }
                    }

                    // 请购单
                    if(this.routePath == '/procurement/purchaseRequisition') {
                        if (item.name == '制单' && !item.value) {
                            this.$set(item, 'value', this.$store.state.user.name)
                        }
                        if (item.name == '制单时间'  && !item.value) {
                            this.$set(item, 'value', getDate.getCurrentMoment().format('YYYY-MM-DD'))
                        }
                    }
                })

                //设置下拉默认选中第一个
                this.dynamicFormData.forEach(element => {
                    this.dynamicFormDataMap.set(element.code + "_" + element.dataTab, element);
                    if (element.columnType == '下拉' && element.val != '') {
                        this.$set(element, 'value', element.val.split(',')[0])
                    }
                    if (element.columnType == '下拉选择' && element.val != '' && element.val != null) {
                        if (element.code == 'qualityInspectionState') {
                            //质检状态
                            this.$set(element, 'value', JSON.parse(element.val)[0].key)
                        } else {
                            if (element.code == 'voucherState') {
                                //console.log('____单据状态', element.val, this.formatSelectJsonVal(element.val))
                            }
                            // let oooo = [];
                            // let valArray = JSON.parse(element.val);
                            // valArray.forEach(item => {
                            //     oooo.push(item)
                            // });
                            let defaultArray = this.formatSelectJsonVal(element.val);
                            if (defaultArray.length > 0) {
                                this.$set(element, 'value', defaultArray[0].key)
                            }
                        }
                    }
                });

                //设置 领退补页面 初始化 默认值
                if (this.isPRF) {
                    this.orderHeaderData.forEach(e => {
                        if (e.code == 'businessType') {
                            this.$set(e, 'value', this.businessType)
                        }
                    });
                }
                if (type == 1) {
                    this.orderId = '';
                    // this.editData = [];
                    for (let i = 0; i < this.orderHeaderData.length; i++) {
                        if (this.orderHeaderData[i].code == 'createdType') {
                            this.$set(this.orderHeaderData[i], 'value', 1)
                        }
                    }
                    this.getCode();//获取单据编号
                    this.initTable();//初始化table

                }
                //console.log("单据表头设计：", this.orderHeaderData)
                // this.dataSourceBom = [];
                // this.dataSourceRoute = [];

            })
        },
        //初始化table数据
        initTable() {
            this.dataSource = [];
            this.reload();
            const dataSource = [];

            //判断屏幕的宽度来设定渲染多少行
            // let w = document.body.clientWidth;//当前可视窗口宽度
            // console.log(w);
            // if(w >= 1920){
            //     this.dataSourceNumber = 10;
            // }

            for (let i = 0; i < this.dataSourceNumber; i++) {
                let array = {
                    number: i + 1,
                };

                dataSource.push(array);
            }
            Object.assign(this.dataSource, dataSource);

            if (!this.isAreaX && this.$route.path !== '/production/productionDemand') {
                this.addTotal();//添加合计
            }
        },

        //添加合计
        addTotal() {
            this.count = this.dataSource.length + 1;

            this.dataSource.push({
                number: "合计",
                name: 'total',
                tax: 0,                  //税额
                // baseQuantity: 0,         //数量
                amount: 0,              //金额
                includeTaxAmount: 0,    //含税金额
                shouldAmount: 0,         //应收金额
            });
            //刷新合计
            this.totalCalculate();
        },
        //提交数据
        submitServer(type) {
            //已查
            //type 在其他页面调用了该组件用type来做必填等相关操作的区分
            //现：type:1.生产订单页面(生单)
            const { dataSource, orderHeaderData, orderFooterData, dynamicFormData } = this;
            //拿出表头、表尾自定义字段
            let customField = dynamicFormData.filter(item => {
                return item.dataType != 1 && (item.dataTab == '表头' || item.dataTab == '表尾');
            })
            //在 深拷贝 前 处理dataSource中的 下拉选择
            dynamicFormData.forEach(element => {
                if (element.columnType == '下拉选择') {
                    dataSource.forEach((item, key) => {
                        item[element.code] = item[element.code + 'Id']
                    })
                }
            });
            let d = {
                detail: _.cloneDeep(dataSource),
                header: orderHeaderData.filter(item => { return item.dataType == 1 }),
                footer: orderFooterData.filter(item => { return item.dataType == 1 }),
                customField: customField,
            }
            //文字转换为id
            for (const key in d.detail) {
                d.detail[key].baseUnit_temp_id ? d.detail[key].baseUnit = d.detail[key].baseUnit_temp_id : '';//主计量
                d.detail[key].subUnit_temp_id ? d.detail[key].subUnit = d.detail[key].subUnit_temp_id : '';//辅计量
            }
            //设置日期默认值
            for (const key in d.header) {
                if (d.header[key].columnType == '日期' && d.header[key].value == '') {
                    d.header[key].value = getDate.getCurrentMoment().format('YYYY-MM-DD');
                }
            }
            //过滤自定义字段
            let defineData = dynamicFormData.filter(item => item.dataType != 1);
            let requestData = this.submitRegData(d, defineData);

            for (const key in orderHeaderData) {
                if (orderHeaderData[key].columnType == '搜索选择') {
                    //用于页面展示 新增...Name字段
                    if (orderHeaderData[key].code.indexOf('Id') != '-1') {
                        let tempname = orderHeaderData[key].code.substring(0, orderHeaderData[key].code.length - 2) + 'Name';

                        this.$set(requestData, tempname, orderHeaderData[key].valueName);
                        this.$set(requestData, orderHeaderData[key].code, orderHeaderData[key].valueId);
                    }
                }
            }

            if (this.orderId) {
                this.$set(requestData, 'id', this.orderId);
            }
            //订金金额判断
            let numReg = /^[0-9][0-9]*(\.[0-9]{1,8})?$/;//整数或者1-8位小数
            if (requestData.earnestMoney && requestData.earnestMoney != null) {
                if (!numReg.test(requestData.earnestMoney)) {
                    this.$message.warning('订金金额只能是数字！')
                    return;
                }
            }

            //必填判断
            let headerAndFooterVerify = this.onFillData.filter(item => item.dataTab == '表头' || item.dataTab == '表尾');
            if (this.headerInWherehouse) {//隐藏表头的仓库字段 同时去除必填 控制
                headerAndFooterVerify.forEach((element, index) => {
                    if (element.code == 'warehouseId') {
                        headerAndFooterVerify.splice(index, 1); //删除下标为i的元素
                    }
                });
            }


            if (this.headerInVendorName) {//隐藏表头的供应商字段 同时去除必填 控制
                headerAndFooterVerify.forEach((element, index) => {
                    if (element.code == 'vendorId') {
                        headerAndFooterVerify.splice(index, 1); //删除下标为i的元素
                    }
                });
            }

            if (this.headerInCrmName) {//隐藏表头的客户字段 同时去除必填 控制
                headerAndFooterVerify.forEach((element, index) => {
                    if (element.code == 'crmId') {
                        headerAndFooterVerify.splice(index, 1); //删除下标为i的元素
                    }
                });
            }


            if (this.isHideDetailsProductId) {//强制去掉  表头  加工产品名称和加工产品编码
                headerAndFooterVerify.forEach((element, index) => {
                    if (element.code == 'productId') {
                        headerAndFooterVerify.splice(index, 1); //删除下标为i的元素
                    }
                });

                headerAndFooterVerify.forEach((element, index) => {
                    if (element.code == 'productCode') {
                        headerAndFooterVerify.splice(index, 1); //删除下标为i的元素
                    }
                });
            }
            for (const key in requestData) {//表头和表尾的必填判断
                for (const onkey in headerAndFooterVerify) {
                    //console.log(requestData, headerAndFooterVerify, 'headerAndFooterVerify')
                    if (key != 'orderDetailList' && headerAndFooterVerify[onkey].code == key && !headerAndFooterVerify[onkey].value && headerAndFooterVerify[onkey].value !== 0) {
                        this.$message.warning(`${headerAndFooterVerify[onkey].name}必须填写!`)
                        return;
                    }
                }
            }

            let detailVerify = this.onFillData.filter(item => item.dataTab == '明细' && item.onEdit)
            let b = requestData.orderDetailList;


            //判断需求日期 必须大于预约到货日期
            for (let i = 0; i < b.length; i++) {
                if (b[i].requireDate && b[i].acceptDate) {
                    //需求日期，到货日期
                    if (this.compareDate(b[i].requireDate, b[i].acceptDate) == false) {
                        this.$message.warning(`第${i + 1}行，到货日期必须在采购日期之前`)
                        return;
                    }
                }

                if (b[i].beginDate && b[i].endDate) {
                    //开工日期，完工日期
                    if (this.compareDate(b[i].endDate, b[i].beginDate) == false) {
                        this.$message.warning(`第${i + 1}行，开工日期必须小于完工日期`)
                        return;
                    }
                }

                if (b[i].needDate && b[i].endDate) {
                    //需求日期必须大于完工日期
                    if (this.compareDate(b[i].needDate, b[i].endDate) == false) {
                        this.$message.warning(`第${i + 1}行，完工日期必须小于需求日期`)
                        return;
                    }
                }
            }



            //采购入库 头部选择仓库过后，明细中仓库同步修改
            if (this.isHideWherehouse) {//isHideWherehouse:证明是采购入库
                requestData.orderDetailList.forEach(cai => {
                    cai.warehouseName = requestData.warehouseName;
                    cai.warehouseId = requestData.warehouseId;
                    cai.warehouseCode = requestData.warehouseCode;
                });
            }

            //采购到货，采购退货  头部有客户的 明细中客户同步
            if (this.isDetailCrmId) {
                if (requestData.crmId) {
                    requestData.orderDetailList.forEach(cai => {
                        cai.crmId = requestData.crmId;
                        cai.crmName = requestData.crmName;
                    });
                }
            }
            //采购订单  头部有供应商的 明细中供应商同步
            if (this.isDetailVendorId) {
                if (requestData.vendorId) {
                    requestData.orderDetailList.forEach(cai => {
                        cai.vendorId = requestData.vendorId;
                        cai.vendorName = requestData.vendorName;
                    });
                }
            }

            if (b.length == 0) {
                this.$message.warning('单据明细不能为空')
                return;
            }
            //console.log("未判断的提交数据：", b);
            // if (b.mrpCode) { //mrp运算生成的单据
            //     this.dataSource[i].baseUnit = this.dataSource[i].unitName;
            // } else {


            // b.forEach(item => {
            //     if (item.mrpCode) {
            //         //mrp运算生成的单据   主计量赋值
            //         item.baseUnit = item.unitId;
            //     }
            // });

            //去掉明细当中工序的必填
            if (this.isDetailRecord) {
                detailVerify = detailVerify.filter(item => item.code != 'procedureId');
            }
            for (const key in b) {//明细的必填判断
                let a = b[key];
                for (const onkey in detailVerify) {
                    //console.log(a[detailVerify[onkey].code])

                    if (this.sourceCode == 'PeriodStartOfStock' && !a[detailVerify[onkey].code]) {
                        //库存期初判断 数量为0 也可以保存
                    } else {

                        if (!a[detailVerify[onkey].code] && a[detailVerify[onkey].code] != 0) {
                            this.$message.warning(`${detailVerify[onkey].name}必须填写!`)
                            return;
                        }
                    }
                }
            }

            //---出入库需要传递的参数
            this.$set(requestData, 'dataSource', this.sourceCode)
            this.$set(requestData, 'receiveDeliverType', this.receiveDeliverType);//1收，2发
            //---出入库需要传递的参数
            //console.log("合并数据来源前:", requestData);
            //合并数据来源
            Object.assign(requestData, this.sourceVoucherData);
            //console.log("数据来源：", this.sourceVoucherData, this.sourceVoucherDetails);

            // if (!requestData.id && requestData.sourceVoucherId) {
            //     //合并明细来源id
            //     for (let i = 0; i < requestData.orderDetailList.length; i++) {
            //         if (!this.sourceVoucherDetails[i]) {
            //             this.$message.warning('生单或选单不允许新增数据');
            //             return;
            //         }
            //         this.$set(requestData.orderDetailList[i], 'sourceDetailId', this.sourceVoucherDetails[i].sourceDetailId);
            //     }
            //     console.log('提交的明细', requestData.orderDetailList, '明细来源id：', this.sourceVoucherDetails);
            // }

            let mxDetails = requestData.orderDetailList;
            //采购发票 判断发票类型和业务类型
            if (this.$route.path == '/procurement/purchaseInvoice') {
                //记录选中的 发票类型
                if (requestData.businessType == 99) {
                    if (this.recordInvoiceType != 0) {
                        this.$message.warning('采购退货时，发票类型必须是“负发票”');
                        return;
                    }
                    // for (let i = 0; i < mxDetails.length; i++) {
                    //     if (mxDetails[i].baseQuantity > 0) {
                    //         this.$message.warning('采购退货时，物料数量必须小于0');
                    //         return;
                    //     }
                    // }
                } else if (requestData.businessType == 1 || requestData.businessType == 2) {
                    if (this.recordInvoiceType == 0) {
                        this.$message.warning('发票类型必须是“正发票”');
                        return
                    }
                }
            }

            //销售发票 判断发票类型和业务类型
            if (this.$route.path == '/sale/saleInvoice') {
                //记录选中的 发票类型
                if (requestData.businessType == 98) {
                    if (this.recordInvoiceType != 0) {
                        this.$message.warning('销售退货时，发票类型必须是“负发票”');
                        return;
                    }
                    // for (let i = 0; i < mxDetails.length; i++) {
                    //     if (mxDetails[i].baseQuantity > 0) {
                    //         this.$message.warning('销售退货时，物料数量必须小于0');
                    //         return;
                    //     }
                    // }

                } else if (requestData.businessType == 3) {
                    if (this.recordInvoiceType == 0) {
                        this.$message.warning('发票类型必须是“正发票”');
                        return
                    }
                }
            }

            //业务为退货的数量必须为 负数
            // if (requestData.businessType == 96 ||
            //     requestData.businessType == 97 ||
            //     requestData.businessType == 98 ||
            //     requestData.businessType == 99 ||
            //     requestData.businessType == 5 ||
            //     requestData.businessType == 31 ||
            //     requestData.businessType == 32 ||
            //     this.businessType == 99
            // ) {
            //     for (let i = 0; i < mxDetails.length; i++) {
            //         if (mxDetails[i].baseQuantity > 0) {
            //             this.$message.warning('业务类型为退货时，物料数量必须是负数');
            //             return;
            //         }
            //     }
            // }
            //领退补页面，业务类型定死
            // if (this.sourceCode == 'RRS') {
            //     requestData.businessType = this.businessType;
            // }
            //采购退货单 业务类型 特殊处理 20210916 白强
            // if (this.$route.path == '/procurement/purchaseExamineReturn' ||
            //     this.$route.path == '/inventory/bills/materialOutRet') {
            //     requestData.businessType = this.businessType;
            // }
            //console.log('提交数据：', requestData)
            //提交保存数据
            if (this.isSaveRun) {
                this.isSaveRun = false;
                let data = requestData.orderDetailList;
                data.forEach(element=>{
                    element.baseUnit = data.baseUnitId
                })
                this.submit(requestData);
            }
        },
        // 格式化传过来的数据
        formatDataSource(dataSource) {
            let result = dataSource ? _.cloneDeep(dataSource) : []
            this.dynamicFormData.forEach(element => {
                if (element.columnType == '下拉选择') {
                    result.forEach((item, key) => {
                        item[element.code] = item[element.code + 'Id']
                    })
                }
            });
            //文字转换为id
            for (const key in result) {
                result[key].baseUnit_temp_id ? result[key].baseUnit = result[key].baseUnit_temp_id : '';//主计量
                result[key].subUnit_temp_id ? result[key].subUnit = result[key].subUnit_temp_id : '';//辅计量
            }
            return result
        },
        /**
         * 修改&&选单&&生单
         * type=='ischoose' 选单
         * type=='iscreate' 生单
         */
        editClickOrder(record, type) {
            //已查
            if (type == 'ischoose' || type == 'iscreate') {
                //删除制单日期，审核日期，变更日期
                this.deleteMainCommonFild(record);
            }
            //this.record
            //如果 是选单的时候，先清当前数据
            if (type == 'ischoose') {
                //console.log("--- 生单，清空表头数据----", this.orderHeaderData);
                //先清空数据
                for (let i = 0; i < this.orderHeaderData.length; i++) {
                    if (this.orderHeaderData[i].columnType == '搜索选择') {
                        this.$set(this.orderHeaderData[i], 'valueId', '');
                        this.$set(this.orderHeaderData[i], 'valueName', '')
                        this.$set(this.orderHeaderData[i], 'value', '')
                    } else {
                        this.$set(this.orderHeaderData[i], 'value', '');
                    }
                }
                this.dynamicFormData.forEach(f => {
                    delete f.value;
                    delete f.valueId;
                    delete f.valueName;
                });
                //end先清空数据
                this.dynamicFormData = deepCopy(this.dynamicFormData, true);
                // this.dynamicFormData = _.cloneDeep(this.dynamicFormData);
                if (record.detailList && record.detailList.length > 0) {
                    record.detailList = record.detailList.filter(f => f.baseQuantity);
                }
            }
            this.thisPageData = record;
            if (this.sourceCode == 'Contract') {
                if (record.orderDetailList && record.orderDetailList.length > 0) {
                    record.detailList = _.cloneDeep(record.orderDetailList);
                }
            }
            //console.log('修改record值', type, record);
            //合同签订多个tabls标签页，防止重复请求获取详情接口 设置限制
            if (this.sourceCode == 'Contract') {
                this.initDetails = true;
                //合同签订 多个明细标签页  刷新跳转到合同标的
                this.activeKeyContract = 1;
            }
            // if (this.$route.path == '/inventory/bills/purchaseIn' ||
            //     this.$route.path == '/inventory/bills/productIn' ||
            //     this.$route.path == '/inventory/bills/delegateIn'
            // ) { //库管员  采购入库单||成品入库单||委外入库单 特殊处理
            //     this.isSource = true;//退单处理
            // } else {
            //     this.isSource = record.sourceVoucherCode ? true : false;//是否有来源单
            // }

            this.createUserId = record.createUserId;//单据创建人id

            if (!type) {
                this.editMask = true;//遮罩
            } else {
                this.editMask = false;
                this.showModel = 'order';
            }

            /*****  1.2.处理 来源单据 ******/
            //如果有 来源单据

            if (record.sourceVoucherType) {
                this.sourceVoucherData = {};
                this.sourceVoucherDetails = [];
                //数据来源
                this.sourceVoucherData = {
                    'sourceVoucherId': record.sourceVoucherId,
                    'sourceVoucherCode': record.sourceVoucherCode,
                    'sourceVoucherDate': record.sourceVoucherDate,
                    'sourceVoucherType': record.sourceVoucherType,
                }
                // 如果 字段设计 没有 业务类型，就直接赋值上一个单据的 业务类型
                if (!this.dynamicFormData.some(c => c.code == 'businessType')) {
                    this.sourceVoucherData.businessType = record.businessType;
                }

                if (this.$route.path == '/production/productionPlan' || this.$route.path == '/production/productionDemand') {
                    //生产订单选销售订单 传值
                    this.$set(this.sourceVoucherData, 'saleOrderId', record.sourceVoucherId);
                    this.$set(this.sourceVoucherData, 'saleOrderCode', record.sourceVoucherCode);
                }
                //处理合同 对方单位 生单的时候 映射 到客户单位上
                if (record.sourceVoucherType == 'Contract') {
                    record.crmId = record.oppositeCompanyId;
                    record.crmName = record.oppositeCompanyName;
                }
                // 如果 选单 或者 生单
                if (type) {
                    //明细中添加数据来源id
                    record.detailList.forEach(element => {
                        element.sourceDetailId = element.id;
                        // this.sourceVoucherDetails.push({
                        //     sourceDetailId: element.id
                        // })
                    });
                    // 去除id （如果是生单或者选单在去除id）
                    record = this.copyRemoveIdData(JSON.stringify(record));
                }
                //领退补
                // this.orderHeaderData.forEach(e => {
                //     if (e.code == 'businessType') {
                //         e.onEdit = false;
                //     }
                // });
            }



            //console.log('==========================当前数据===================', record)
            //去掉明细当中工序的必填
            if (record.detailList) {
                if (this.routePath == '/procurement/purchaseRequisition' || this.routePath == '/procurement/purchaseOrder') {
                    record.detailList.forEach(item => {
                        item.requireDate = item.planBeginDate
                        item.acceptDate = moment(item.planBeginDate).subtract(item.purchasingLeadTime - 1, 'days').format('YYYY-MM-DD')
                    })
                }

                this.dataSource = record.detailList.map((item,index)=> {
                    return {
                        ...item,
                        //baseUnitId : item.baseUnit,
                        //baseUnit : item.baseUnitName,
                        baseUnitId: item.baseUnit_temp_id,
                        baseUnit_temp_id : item.baseUnit,
                        baseUnit : item.baseUnitName,

                        operationQuantity: item.baseQuantity,
                        operationNumber: item.baseQuantity,
                        number: index + 1,
                        // sourceVoucherTypeId : item.sourceVoucherType == "MasterProductionSchedule" ? "MasterProductionSchedule" : "SaleOrder",
                        // sourceVoucherType : item.sourceVoucherType == "MasterProductionSchedule" ? "主生产计划" : "销售订单"
                    }
                });
                this.record = record;
                this.computedData = this.dataSource
                this.detailObj = {...record }
            } else {
                return false;
            }
            if (record.planList && record.planList.length > 0) {
                this.planDataSource = record.planList;//计划数据（仅供财务使用）
            }

            this.orderId = record.id;
            //console.log('--------this.orderId = record.id;----------', this.orderId);
            this.voucherState = record.voucherState;
            this.closedState = record.closedState;

            this.enableState = record.enableState;    //启用 停用
            /***** 特殊处理 加工单和委外加工单 ******/
            if ((this.$route.path == '/production/productionWork' || this.$route.path == '/outsource/outProductionWork')) {
                this.dataSourceBom = [];
                this.dataSourceRoute = [];
                if ((type == 'ischoose' || type == 'iscreate')) {
                    for (let i = 0; i < this.dataSource.length; i++) {
                        let detail = this.dataSource[i];
                        let { bomId, baseQuantity, processRouteId } = detail;
                        //console.log("生单 + 选单：查询bom明细：", detail, bomId, baseQuantity, processRouteId)
                        if (bomId) {
                            this.getBomDetails2(bomId, baseQuantity, 1, detail);
                            detail.bomExpMethod = 1;
                        }
                        if (processRouteId) {
                            this.getRouteDetails2(processRouteId, detail);
                        }
                    }
                }
                let index = this.classWorkCurrent || 0;
                if (this.dataSource[0] && this.dataSource.length > index) {
                    //委外加工单 和 加工单 获取物料明细
                    //默认显示第一条数据的物料明细和工序明细
                    this.dataSourceBom = this.dataSource[index].productionWorkInventoryDetailList;
                    this.dataSourceRoute = this.dataSource[index].productionWorkProcedureDetailList;
                }
                this.reloadWork();

            }
            //修改数据时（如果单据类型是 自制工序检验 则隐藏明细当中的工序）
            if (record.businessType == '44') {
                this.isDetailRecord = false;
                this.columns = this.regroupTableColumns(this.orderDetailData);
            }

            let detailList = this.dataSource.map((element,index)=> {
                return {
                    ...element,
                    // baseUnitId: element.baseUnit,
                    // baseUnit_temp_id : element.baseUnit,
                    // baseUnit : element.baseUnitName,

                    bussessPlanId : element.bussessPlan,
                    bussessPlan : element.bussessPlan == 1 ? "采购" : element.bussessPlan == 2 ? "自制" : element.bussessPlan ? "委外" : "",
                    releaseStateId: element.releaseState ? element.releaseState : "",
                    releaseState: element.releaseState == 1 ? "未下达" : element.releaseState == 2 ? "部分下达" : element.releaseState ? "全部下达" : "",
                }
            });
            this.detailList = detailList
            this.$store.commit('SET_MRP_COPY', detailList)


            //补足表格
            if (this.dataSource.length < this.dataSourceNumber) {
                for (let i = this.dataSource.length; i < this.dataSourceNumber; i++) {
                    let array = {
                        number: i + 1,
                    };
                    this.dataSource.push(array);
                }
                this.addTotal();//添加合计
            } else {
                for (let i = 0; i < 2; i++) {
                    let array = {
                        number: i + 1,
                    };
                    this.dataSource.push(array);
                }
                this.addTotal();//添加合计
            }

            this.reload()
            //自定义字段
            let defineData = this.dynamicFormData.filter(item => item.dataType != 1);

            /*****  2.处理 单据明细 相同事件 ******/
            for (let i = 0; i < this.dataSource.length; i++) {
                if (this.dataSource[i].unitGroupId) {
                    this.dataSource[i].unitId = null;
                    //多计量
                    this.dataSource[i].baseUnit_temp_id = this.dataSource[i].baseUnit;//多计量
                    this.dataSource[i].baseUnit = this.dataSource[i].baseUnitName;
                    //辅助计量数据
                    this.unitsAssistSelect = this.returnGroupUnits(this.dataSource[i].unitGroupId);
                    //辅助计量修改时设值
                    let findSubUnit = this.unitsAssistSelect.find(item => item.id == this.dataSource[i].subUnit);
                    if (!findSubUnit) {
                        findSubUnit = this.unitsAssistSelect.filter(item => !item.isMainUnit)[0];
                    }
                    if (findSubUnit) {
                        this.dataSource[i].subUnit = findSubUnit.name;
                        this.dataSource[i].subUnit_temp_id = findSubUnit.id;
                        this.dataSource[i].subUnitName = findSubUnit.name;
                        this.dataSource[i].unitExchangeRate = findSubUnit.changeRate;  //换算率
                        if (!this.dataSource[i].subQuantity) {
                            this.dataSource[i].subQuantity = (Number(this.dataSource[i].baseQuantity) / Number(findSubUnit.changeRate)).toFixed(4);
                        }
                    }
                    // this.unitsAssistSelect.forEach(item => {
                    //     if (item.id == this.dataSource[i].subUnit) {
                    //         this.dataSource[i].subUnit = item.name;
                    //         this.dataSource[i].subUnit_temp_id = item.id;
                    //         this.dataSource[i].subUnitName = item.name;
                    //         this.dataSource[i].unitExchangeRate = item.changeRate;  //换算率
                    //     }
                    // })
                } else if (this.dataSource[i].unitId) {
                    //单计量
                    this.dataSource[i].baseUnit_temp_id = this.dataSource[i].unitId;
                    this.dataSource[i].baseUnit = this.dataSource[i].baseUnitName;
                }


                //明细自定义值的转换
                if (this.dataSource[i].defineFields) {
                    let defineItem = JSON.parse(this.dataSource[i].defineFields);
                    for (const dekey in defineItem) {
                        for (const allkey in defineData) {
                            //根据id找到code
                            if (defineData[allkey].code == dekey) {
                                this.$set(this.dataSource[i], defineData[allkey].code, defineItem[dekey])
                            }
                        }
                    }
                }

                //是否
                this.dynamicFormData.forEach(element => {
                    if (element.columnType == '下拉选择') {
                        for (const key in this.dataSource[i]) {
                            if (element.code == key) {
                                //1：当前选中的id  2：下拉数组
                                let label = this.handleDownChoice(this.dataSource[i][key], element.val);
                                this.$set(this.dataSource[i], key + 'Id', this.dataSource[i][key])
                                this.$set(this.dataSource[i], key, label)
                            }
                        }
                    }

                    if (element.columnType == '是否') {
                        element.value = record[element.code];
                    }

                    if (element.columnType == '复选') {
                        for (const key in this.dataSource[i]) {
                            if (element.code == key) {
                                this.$set(this.dataSource[i], key, this.dataSource[i][key] ? '是' : '否')
                            }
                        }
                    }
                });
            }
            /*****  3.处理 "明细"单据设计  ******/
            for (let d = 0; d < this.orderDetailData.length; d++) {
                if (record.sourceVoucherCode != null && record.sourceVoucherCode != '') {//判断是否有来源code
                    //生单和选单过来的数据 明细不可修改字段
                    let array = ['inventoryCode', 'inventoryId'];
                    let checkArray = (code) => {
                        return array.includes(code);
                    }
                    if (checkArray(this.orderDetailData[d].code)) {
                        this.$set(this.orderDetailData[d], 'onEdit', false);
                    }
                    record.detailList.forEach(item => {
                        //退货业务数量金额都是负数
                        // if (item.baseQuantity > 0) {
                        //     if (record.businessType == 31 || record.businessType == 32 || record.businessType == 96 || record.businessType == 97 || record.businessType == 98 || record.businessType == 99 || record.businessType == 5 || this.businessType == 1 || this.businessType == 99) {
                        //         console.log('之前', item.baseQuantity, item.tax, item.amount, item.includeTaxAmount);
                        //         item.baseQuantity = -Number(item.baseQuantity);
                        //         item.orgBaseQuantity = item.baseQuantity;
                        //         item.subQuantity = -Number(item.subQuantity);
                        //         if (item.tax > 0) {
                        //             item.tax = -Number(item.tax);
                        //             item.amount = -Number(item.amount);
                        //             item.includeTaxAmount = -Number(item.includeTaxAmount);
                        //         }
                        //         console.log('之后', item.baseQuantity, item.tax, item.amount, item.includeTaxAmount);
                        //     }
                        // }
                    });
                }
            }
            /*****  4.处理 "表头"单据设计  ******/
            let partnerType = null;//往来单位类型
            console.log(record);
            for (let i = 0; i < this.orderHeaderData.length; i++) {
                if (record.sourceVoucherCode != null && record.sourceVoucherCode != '' && this.$route.path != '/production/management/productionOrder') {//判断是否有来源code
                    //生单和选单过来的数据 表头不可修改字段
                    let array = ['crmId', 'crmName'];
                    let checkArray = (code) => {
                        return array.includes(code);
                    }
                    if (checkArray(this.orderHeaderData[i].code)) {
                        this.$set(this.orderHeaderData[i], 'onEdit', false);
                    }
                }
                for (const key in record) {
                    /*****  处理 "表头"单据设计 ---  往来单位类型 ******/
                    if (this.orderHeaderData[i].code == key) {
                        if (this.orderHeaderData[i].code == 'partnerType') {
                            //往来类型
                            //console.log('往来类型：', record[key])
                            partnerType = record[key];
                        }
                    }
                    if (this.orderHeaderData[i].code == key) {

                        if (this.orderHeaderData[i].columnType == '搜索选择') {
                            //用于页面展示 新增...Name字段
                            if (this.orderHeaderData[i].code.indexOf('Id') != '-1') {
                                if (this.orderHeaderData[i].code == 'partnerId') {
                                    //往来单位
                                    if (partnerType == 1) {//供应商
                                        this.$set(this.orderHeaderData[i], 'val', 'supplie');
                                    } else if (partnerType == 2) {//客户
                                        this.$set(this.orderHeaderData[i], 'val', 'crm');
                                    } else if (partnerType == 3) {//员工
                                        this.$set(this.orderHeaderData[i], 'val', 'employees');
                                    } else if (partnerType == 4) {//部门
                                        this.$set(this.orderHeaderData[i], 'val', 'office');
                                    } else {
                                        this.$set(this.orderHeaderData[i], 'val', 'crm');
                                    }
                                }
                                let tempname = this.orderHeaderData[i].code.substring(0, this.orderHeaderData[i].code.length - 2) + 'Name';
                                this.forceRerender();
                                setTimeout(() => {
                                    this.$set(this.orderHeaderData[i], 'valueId', record[key]);
                                    this.$set(this.orderHeaderData[i], 'valueName', record[tempname])
                                    this.$set(this.orderHeaderData[i], 'value', record[tempname])
                                }, 500)
                            }
                            if (this.orderHeaderData[i].code == 'warehouseId') {
                                this.newWarehouseId = record['warehouseId'];
                            }
                        } else {
                            //如果是选单（选单等于新增） 单据编号不赋值
                            if (type == 'ischoose' || type == 'iscreate') {
                                if (this.orderHeaderData[i].code != 'voucherCode') {
                                    this.$set(this.orderHeaderData[i], 'value', record[key]);
                                }
                            } else {
                                if(this.routePath == '/sale/saleOrder'){
                                    if(this.orderHeaderData[i].code == "outboundStatus"){
                                        this.$set(this.orderHeaderData[i], 'value', parseInt(record[key]));
                                    }
                                    if(this.orderHeaderData[i].code == "paymentStatus"){
                                        this.$set(this.orderHeaderData[i], 'value', parseInt(record[key]));
                                    }
                                    if(this.orderHeaderData[i].code == "executionStatus"){
                                        this.$set(this.orderHeaderData[i], 'value', parseInt(record[key]));
                                    }
                                } else {
                                   this.$set(this.orderHeaderData[i], 'value', record[key]);
                                }
                            }
                        }
                        //采购发票，采购入库，销售出库
                        if (this.orderHeaderData[i].code == 'businessType' &&
                            (this.sourceCode == 'PurchaseInvoice' || this.sourceCode == 'PurchaseReceiveVoucher' || this.businessType == 5)) { //材料退料单 ，委外材料退料单
                            this.$set(this.orderHeaderData[i], 'onEdit', false);
                        }

                        // 退货单 选单时候，业务类型的更改
                        if (this.orderHeaderData[i].code == 'businessType') {

                            //采购退货99，采购退货（冲抵）97
                            if (this.sourceCode == 'PuArrival' && this.businessType == 1) {
                                if (record.businessType != 99 && record.businessType != 97) {
                                    this.$set(this.orderHeaderData[i], 'value', 99);
                                    this.$set(this.orderHeaderData[i], 'onEdit', true);
                                } else {
                                    this.$set(this.orderHeaderData[i], 'value', record.businessType);
                                }
                            }

                            //销售退货 98,销售退货（冲抵）96
                            if (this.sourceCode == 'SaleDelivery' && this.businessType == 1) {
                                if (record.businessType != 98 && record.businessType != 96) {
                                    this.$set(this.orderHeaderData[i], 'value', 98);
                                    this.$set(this.orderHeaderData[i], 'onEdit', true);
                                } else {
                                    this.$set(this.orderHeaderData[i], 'value', record.businessType);
                                }
                            }


                            //1：当前选中的id  2：下拉数组
                            let thisBusinessType = this.handleDownChoice(record.businessType, this.orderHeaderData[i].val);
                            //处理生单或者选单 在当前单据中  没有该“下拉选择”的选择时   （默认选中第一个）
                            if (!thisBusinessType) {
                                this.$set(this.orderHeaderData[i], 'value', JSON.parse(this.orderHeaderData[i].val)[0].key);
                            }

                            if (this.$route.path == '/quality/qualityDetection') {
                                //根据检验单来源  控制 固定业务类型不可改
                                if (record.sourceVoucherType == 'PuArrival') {
                                    //采购到货单
                                    this.$set(this.orderHeaderData[i], 'value', 41);
                                    this.$set(this.orderHeaderData[i], 'onEdit', false);

                                } else if (record.sourceVoucherType == 'DelegateArrival') {
                                    //委外加工
                                    this.$set(this.orderHeaderData[i], 'value', 42);
                                    this.$set(this.orderHeaderData[i], 'onEdit', false);

                                } else if (record.sourceVoucherType == 'ProductionFinish') {
                                    //生产完工
                                    this.$set(this.orderHeaderData[i], 'value', 43);
                                    this.$set(this.orderHeaderData[i], 'onEdit', false);
                                }
                            }

                        }

                        //发票类型负发票 标题变红
                        // if ((this.$route.path == '/procurement/purchaseInvoice' || this.$route.path == '/sale/saleInvoice') && this.orderHeaderData[i].code == 'invoiceTypeId') {
                        //     //记录选中的 发票类型
                        //     console.log('红不红：',this.orderHeaderData[i])
                        //     this.recordInvoiceType = this.orderHeaderData[i].value;
                        //     if (this.recordInvoiceType == 0) {
                        //         document.querySelectorAll("h2.text-center")[0].style.color = 'red'
                        //     } else {
                        //         document.querySelectorAll("h2.text-center")[0].style.color = 'rgba(0,0,0,.85)'
                        //     }
                        // }
                    }
                    //特殊处理，报价单的客户和其他单据客户 字段不一样（*** 选单 ***）
                    if ((type == 'ischoose' || type == 'iscreate') && this.orderHeaderData[i].code == 'crmId' && this.sourceCode == 'SaleOrder') {
                        this.$set(this.orderHeaderData[i], 'valueId', record['crmCustomerId']);
                        this.$set(this.orderHeaderData[i], 'valueName', record['crmCustomerName'])
                        this.$set(this.orderHeaderData[i], 'value', record['crmCustomerName'])
                    }
                }

                //头部自定义值的转换
                if (record.defineFields) {
                    let recoedDefine = JSON.parse(record.defineFields)
                    for (const key in recoedDefine) {
                        if (this.orderHeaderData[i].code == key) {
                            this.$set(this.orderHeaderData[i], 'value', recoedDefine[key]);
                        }
                    }
                }

            }

            console.log(this.dataSource);
            console.log(this.orderHeaderData);

            setTimeout(() => {
                if(this.$route.path == '/sale/saleOrder'){
                    this.orderHeaderData.forEach(element=>{
                        if(element.code == 'voucherDate'){
                            this.$set(element, 'value', record.voucherDate);
                        }
                        if(element.code == 'voucherCode'){
                            this.$set(element, 'value', record.voucherCode);
                        }
                    })
                }
            }, 1000);

            for (let i = 0; i < this.orderHeaderData.length; i++) {
                if(this.orderHeaderData[i].name == "MRP运算方案" && this.orderHeaderData[i].code == "chooseSchemeId"){
                    this.$set(this.orderHeaderData[i], 'value', record.chooseSchemeName);
                }
            }


            /*****  5.处理 "表尾"单据设计  ******/
            for (let i = 0; i < this.orderFooterData.length; i++) {
                for (const key in record) {
                    if (this.orderFooterData[i].code == key) {
                        if (this.orderFooterData[i].columnType == '搜索选择') {
                            if (this.orderFooterData[i].code.indexOf('Id') != -1) {
                                let tempname = this.orderFooterData[i].code.substring(0, this.orderFooterData[i].code.length - 2) + 'Name';
                                this.$set(this.orderFooterData[i], 'valueId', record[key]);
                                this.$set(this.orderFooterData[i], 'valueName', record[tempname])
                                this.$set(this.orderFooterData[i], 'value', record[tempname])
                                //console.log(this.orderFooterData);
                            }
                        } else {
                            if (this.orderFooterData[i].code == key) {
                                this.$set(this.orderFooterData[i], 'value', record[key])
                            }
                        }
                    }
                }

                //底部自定义值的转换
                if (record.defineFields) {
                    let recoedDefine = JSON.parse(record.defineFields)
                    for (const key in recoedDefine) {
                        if (this.orderFooterData[i].code == key) {
                            this.$set(this.orderFooterData[i], 'value', recoedDefine[key]);
                        }
                    }
                }
            }

            this.loading = false;
            //console.log('--------this.loading = false;this.orderId----------', this.orderId);
            /*****  6.清空 "生单"来源数据  ******/
            setTimeout(() => {
                this.$store.commit('SET_ARR', {})
            }, 1000);
            /*****  刷新面积计算表 表格的数据  ******/
            setTimeout(() => {
                if (this.isAreaX) {
                    //刷新面积计算表 表格的数据
                    this.dataSource.forEach((item, index) => {
                        item.number = index + 1;
                    });
                    this.$refs.plxTable.reloadData(this.dataSource)
                }
            }, 600)
            /*****  选单时 获取单据编号  ******/
            if (type == 'ischoose') {
                this.getCode();//获取单据编号
            }

            if (this.$route.path == '/production/productionPlan' || this.$route.path == '/production/productionDemand') {
                for (let i = 0; i < this.orderHeaderData.length; i++) {
                    if (this.orderHeaderData[i].code == 'createdType') {
                        this.$set(this.orderHeaderData[i], 'value', 0)
                        //this.$set(this.orderHeaderData[i], 'value', this.orderHeaderData[i].value)
                    }
                }
                for (let i = 0; i < this.orderFooterData.length; i++) {
                    if (this.orderFooterData[i].code == 'voucherState') {
                        this.$set(this.orderFooterData[i], 'value', this.orderFooterData[i].value)
                    }
                }
            }

        },
        //物料单选 OR 其他change事件
        onCellChange(indexTable, dataIndex, value, type) {
            if(this.$route.path == '/production/productionPlan'){
                if(dataIndex == 'productionLeadTime' && typeof value == 'number'){
                    if(Number(value) < 1){
                        value = 1
                    }
                }
            }

            //修改明细table数据
            let dataSource = [...this.dataSource];
            const target = dataSource.find((item, index) => index === indexTable);
            let runAddDataSource = true;
            if (dataIndex == 'adjustRate' || dataIndex == 'adjustQuantity' || dataIndex == 'operationNumber') {
                //调整比例，调整数量，运算数量
                if (dataIndex == 'adjustRate') {
                    if (value) {
                        //运算数量=数量 *（调整比例/100）
                        target['adjustQuantity'] = (Number(target.baseQuantity) * (value / 100)).toFixed(2);
                        //setTimeout(() => {
                            target['operationNumber'] = (Number(target.adjustQuantity) + Number(target.baseQuantity)).toFixed(2);
                        //},500)
                    }
                }
                if (dataIndex == 'adjustQuantity') {
                    if (value) {
                        //调整比例=数量/调整数量 * 100 adjustRate baseQuantity
                        target['adjustRate'] = (value / Number(target.baseQuantity) * 100).toFixed(2);
                        //setTimeout(() => {
                            target['operationNumber'] = (Number(value) + Number(target.baseQuantity)).toFixed(2);

                        //},500)
                    }
                }
                if (dataIndex == 'operationNumber') {
                    if (value) {
                        //调整比例=数量/调整数量* 100
                        target['adjustQuantity'] = (value - Number(target.baseQuantity)).toFixed(2);
                        //setTimeout(() => {
                            target['adjustRate'] = ((value / Number(target.baseQuantity)) * 100).toFixed(2);
                        //},500)
                    }
                }
            }
            //deliveryDate productionLeadTime  planBeginDate planEndDate
            if (dataIndex === 'productionLeadTime') {
                target.planBeginDate = moment(target.planEndDate).subtract(value - 1, 'days').format('YYYY-MM-DD')
            }
            if (dataIndex === 'planEndDate') {
                target.planBeginDate = moment(value.value).subtract(target.productionLeadTime - 1, 'days').format('YYYY-MM-DD')
            }
            if (dataIndex === 'needDate') {
                target.planEndDate = value.value
            }
            if (dataIndex === 'planBeginDate') {
                let totalDays,diffDate
                let myDate_1 = Date.parse(target.deliveryDate)
                let myDate_2 = Date.parse(value.value)
                // 将两个日期都转换为毫秒格式，然后做差
                diffDate = Math.abs(myDate_1 - myDate_2 + 86400000) // 取相差毫秒数的绝对值
                totalDays = Math.floor(diffDate / (1000 * 3600 * 24)) // 向下取整
                target.productionLeadTime = totalDays
            }

            if (dataIndex === 'deliveryDate') {
                target.planEndDate = moment(value.value).subtract(target.deliveryDate, 'days').format('YYYY-MM-DD')
            }
            console.log(target);
            //处理 工序工价 页面，
            if (this.sourceCode == 'ProcedurePrice' && dataIndex == 'wagesType') {
                target.unitName = value.id ? (value.id == 1 ? "件" : "小时") : ""
            }

            if (dataIndex == 'inventoryCode' || dataIndex == 'inventoryName') {
                //选取物料后重置当前列数据
                for (const key in target) {
                    if (key != 'warehouseName' && key != 'warehouseId' && key != 'warehouseCode') {
                        target[key] = ''
                    }
                }

                //判断物料是否重复（加工单 和 委外加工单 物料不能重复）
                if (this.$route.path == '/production/productionWork' || this.$route.path == '/outsource/outProductionWork') {
                    for (let i = 0; i < this.dataSource.length; i++) {
                        if (value.id == this.dataSource[i].inventoryId) {
                            this.$message.warning('物料已经存在当前单据,不能重复添加', 1);
                            runAddDataSource = false;
                            break;
                        }
                    }
                }


                //物料名称
                if (target && runAddDataSource) {
                    target['inventoryCode'] = value.inventoryCode;//物料编码
                    target['inventoryId'] = value.id;//物料名称
                    target['inventoryName'] = value.inventoryName;//物料名称
                    target['inventorySpecification'] = value.inventorySpecification;//规格型号
                    target['inventoryDescript'] = value.inventoryDescript;//规格型号
                    target['taxRate'] = value.taxRate ? value.taxRate : 0;//税率
                    //含税单价 赋值
                    if (this.saleVoucherArr.includes(this.sourceCode)) {
                        // alert("sourceCode:"+this.sourceCode+",售价：")
                        target.includeTaxPrice = value.sellingPrice || value.refSellingPrice || value.minSellingPrice || 0.00;
                    } else {
                        // alert("sourceCode:"+this.sourceCode+",成本价：")
                        target.includeTaxPrice = value.latestCost ? value.latestCost : value.referenceCost ? value.referenceCost : '';//单价（最新成本or参考成本）
                    }
                    //计算 单价
                    target['price'] = (Number(target.includeTaxPrice) / (1 + (target.taxRate || 0) / 100)).toFixed(2);
                    // target['price'] = value.latestCost ? value.latestCost : value.referenceCost ? value.referenceCost : '';//单价（最新成本or参考成本）
                    target['inventoryCategoryName'] = value.inventoryCategoryName;//存货分类
                    target['inventoryCategoryId'] = value.inventoryCategoryId;  //存货分类id
                    target['commodityAttribute'] = value.commodityAttribute;    //存货商品属性


                    //处理库存初期，仓库
                    this.orderHeaderData.forEach(element => {
                        if (element.code == 'warehouseId') {
                            // if (!element.valueId) {
                            //     this.$message.warning('请先选择仓库');
                            //     return false;
                            // }
                            target['warehouseId'] = element.valueId;
                            target['warehouseName'] = element.valueName;

                            this.getNowQuantityFun([value.id], element.valueId);
                        }
                    });


                    if (value.unitType == '单计量') {
                        // target['baseUnit'] = value.unitName;//单计量
                        // target['baseUnitName'] = value.unitName;//单计量
                        // target['baseUnit_temp_id'] = value.unitId;//单计量id
                        // target['unitId'] = value.unitId;//单计量id

                        target['baseUnit'] = value.unitName;
                        target['baseUnitName'] = value.unitName;
                        target['baseUnit_temp_id'] = value.unitId;

                        target['unitId'] = value.unitId;//用于区分返回值 是否是单计量
                    } else {
                        // for (let i = 0; i < this.unitsDataDetails.length; i++) {
                        //     if (this.unitsDataDetails[i].id == value.mainUnit) {
                        //         target['baseUnit'] = this.unitsDataDetails[i].name;//主计量
                        //         target['baseUnitName'] = this.unitsDataDetails[i].name;//主计量
                        //         target['baseUnit_temp_id'] = this.unitsDataDetails[i].id;//主计量id
                        //         target['baseUnitId'] = this.unitsDataDetails[i].id;
                        //         target['unitGroupId'] = this.unitsDataDetails[i].id;
                        //     }
                        // }
                        target['baseUnit'] = value.mainUnitName;
                        target['baseUnitName'] = value.mainUnitName;
                        target['baseUnit_temp_id'] = value.mainUnit;

                        target['unitGroupId'] = value.unitGroupId; //用于区分返回值是否是多计量
                        // }
                        // if (value.unitType == '多计量') {
                        //辅助计量数据
                        this.unitsAssistSelect = [];
                        this.unitsDataDetails.forEach(element => {
                            if (element.unitGroupId == value.unitGroupId && !element.isMainUnit) {//&& !element.isMainUnit
                                this.unitsAssistSelect.push(element);
                            }
                        });


                        //辅助计量设置默认值
                        this.unitsAssistSelect.forEach(item => {
                            //(采购)
                            if (this.sourceCode == 'PurchaseRequisition' || this.sourceCode == 'PurchaseOrder' || this.sourceCode == 'PuArrival' || this.sourceCode == 'PurchaseInvoice' || this.sourceCode == 'PurchaseReceiveVoucher') {
                                if (item.id == value.purUnit) {
                                    target['subUnit'] = item.name;
                                    target['subUnit_temp_id'] = item.id;
                                    target['subUnitName'] = item.name;
                                    target['unitExchangeRate'] = item.changeRate;  //换算率
                                }
                            } else {
                                //(销售和其他)
                                if (item.id == value.saleUnit) {
                                    target['subUnit'] = item.name;
                                    target['subUnit_temp_id'] = item.id;
                                    target['subUnitName'] = item.name;
                                    target['unitExchangeRate'] = item.changeRate;  //换算率
                                }
                            }
                        });
                    }
                }
            } else if (dataIndex == 'productName' || dataIndex == 'productCode') {
                //对应产品名称，对应产品编码
                target['productName'] = value.inventoryName;
                target['productId'] = value.id;
                target['productCode'] = value.inventoryCode;
                target['productSpecification'] = value.inventorySpecification;
                target['inventoryDescript'] = value.inventoryDescript;
            } else if (dataIndex == 'projectCode' || dataIndex == 'projectName') {
                //项目
                if (dataIndex == 'projectCode') {
                    target[dataIndex] = value.code;
                    target['projectId'] = value.id;
                } else {
                    target[dataIndex] = value.name;
                    target['projectId'] = value.id;
                }

            } else if (dataIndex == 'settleName') {
                //结算方式
                if (value) {
                    target[dataIndex] = value.name;
                    target['settleId'] = value.id;
                    if (value.name == null) {
                        target[dataIndex] = null;
                        target['settleId'] = null;
                    }
                }
            } else if (dataIndex == 'bankName' || dataIndex == 'bankAccount') {
                //银行
                target['bankId'] = value.id;
                target['bankName'] = value.bankName;
                target['bankAccount'] = value.bankAccount;

            } else if (dataIndex == 'warehouseName') {
                //仓库
                target[dataIndex] = value.whName;
                target['warehouseId'] = value.id;
                target['warehouseCode'] = value.whCode;
            } else if (dataIndex == 'crmName') {
                //客户
                target[dataIndex] = value.crmName;
                target['crmId'] = value.id;

            } else if (dataIndex == 'vendorName') {
                //供应商
                target[dataIndex] = value.name;
                target['vendorId'] = value.id;

            } else if (dataIndex == 'invoiceTypeName') {
                //发票类型
                target[dataIndex] = value.name;
                target['invoiceTypeId'] = value.id;

            } else if (dataIndex == 'officeName' || dataIndex == 'officeId') {
                //车间，部门
                //id和name相反,？，编辑项为什么要返回offceid\
                if (dataIndex == 'officeId') {
                    target[dataIndex] = value.officeName;
                    target['officeName'] = value.id;
                } else {
                    target[dataIndex] = value.officeName;
                    target['officeId'] = value.id;
                }


            } else if (dataIndex == 'inventoryLocationCode' || dataIndex == 'inInventoryLocationCode' || dataIndex == 'outInventoryLocationCode') {
                //console.log("货位 编码:", value);
                //货位 编码
                let prefix = dataIndex.replace("Code", "");
                target[dataIndex] = value.code;
                target[prefix + 'Id'] = value.id;
                target[prefix + 'Name'] = value.name;
            } else if (dataIndex == 'inventoryLocationName' || dataIndex == 'inInventoryLocationName' || dataIndex == 'outInventoryLocationName') {
                //console.log("货位 名称:", value);
                //货位
                let prefix = dataIndex.replace("Name", "");
                target[dataIndex] = value.name;
                target[prefix + 'Id'] = value.id;
                target[prefix + 'Code'] = value.code;
            } else if (dataIndex == 'workProcedureName') {
                //工序
                target[dataIndex] = value.name;
                target['workProcedureId'] = value.id;
            } else if (dataIndex == 'procedureName') {
                //委外工序
                if (value) {
                    if (this.routePath == '/production/productionProcessReport') {
                        //("--工序汇报单选择工序--01--", value);
                        //工序汇报单
                        target.qualifiedPrice = value.lastQualifiedPrice || value.qualifiedPrice || 0.00;
                        target.reworkPrice = value.lastReworkPrice || value.reworkPrice || 0.00;
                        target.unqualifiedPrice = value.lastUnqualifiedPrice || value.unqualifiedPrice || 0.00;
                        target.scrapPrice = value.lastScrapPrice || value.scrapPrice || 0.00;
                        target.workHourPrice = value.lastWorkHourPrice || value.workHourPrice || 0.00;
                        let { procedureFlag, procedureId, procedureName, procedureCode, procedureOrder, procedurePriceDetailId, processRouteDetailId } = value;
                        Object.assign(target, { procedureFlag, procedureId, procedureName, procedureCode, procedureOrder, procedurePriceDetailId, processRouteDetailId });
                        let wagesTypeDesign = this.dynamicFormDataMap.get("wagesType_明细");
                        if (wagesTypeDesign && wagesTypeDesign.columnType == '下拉选择') {
                            let label = this.handleDownChoice(value.wagesType, wagesTypeDesign.val);
                            target["wagesType"] = label;
                            target["wagesType" + 'Id'] = value.wagesType;
                        } else {
                            target.wagesType = value.wagesType;
                        }

                        // for (const key in value) {
                        //     if (key == 'lastQualifiedPrice' && value[key] && value[key] != 0) {
                        //         target['qualifiedPrice'] = value[key]
                        //     } else if (key == 'lastReworkPrice' && value[key] && value[key] != 0) {
                        //         target['reworkPrice'] = value[key]
                        //     } else if (key == 'lastUnqualifiedPrice' && value[key] && value[key] != 0) {
                        //         target['unqualifiedPrice'] = value[key]
                        //     } else if (key == 'lastScrapPrice' && value[key] && value[key] != 0) {
                        //         target['scrapPrice'] = value[key]
                        //     } else {
                        //         if (key != 'processRouteName' && key != 'processRouteId') {
                        //             target[key] = value[key]
                        //         }
                        //     }
                        // }
                        //console.log("--工序汇报单选择工序--02--", target);
                    } else {
                        target['procedureName'] = value.name;
                        target['procedureId'] = value.id;
                    }

                }
            } else if (dataIndex == 'productionLineName') {
                //生产线
                target[dataIndex] = value.name;
                target['productionLineId'] = value.id;
            } else if (dataIndex == 'teamName') {
                //班组
                target[dataIndex] = value.name;
                target['teamId'] = value.id;
            } else if (dataIndex == 'bomName') {
                //bom版本号
                target[dataIndex] = value.name;
                target['bomId'] = value.id;
                target['bomExpMethod'] = '单阶';
                target['bomExpMethodId'] = 1;

                //委外加工单获取物料明细
                // this.dataSourceBom = this.dataSourceBom.filter(b => b.bomId != value.id);//防止重新选择相同的bom版本，数据叠加重复
                if (this.$route.path == '/production/productionWork' || this.$route.path == '/outsource/outProductionWork') {
                    this.dataSourceBom = this.dataSourceBom.filter(res => res.inventoryId);
                    if (this.dataSourceBom && this.dataSourceBom.length > 0) {
                        let _this = this;
                        this.$confirm({
                            title: "提示",
                            content: (
                                <span>
                                    物料明细中已经存在数据，是否覆盖物料明细数据?
                                </span>
                            ),
                            onOk() {
                                _this.getBomDetails(value.id, target.baseQuantity, 1);
                                if (value.processRouteId) {
                                    //如果选择的物料明细中有默认工艺路线
                                    target['processRouteName'] = value.processRouteName;
                                    target['processRouteId'] = value.processRouteId;
                                    _this.getRouteDetails(value.processRouteId);
                                }
                            },
                            onCancel() { },
                        });
                    } else {
                        this.getBomDetails(value.id, target.baseQuantity, 1);
                        if (value.processRouteId) {
                            //如果选择的物料明细中有默认工艺路线
                            target['processRouteName'] = value.processRouteName;
                            target['processRouteId'] = value.processRouteId;
                            this.getRouteDetails(value.processRouteId);
                        }
                    }
                }
            } else if (dataIndex == 'bomExpMethod') {
                let { bomId } = target;
                if (!bomId) this.$message.warning(`请先选择BOM!`)
                target['bomExpMethod'] = value.name;
                target['bomExpMethodId'] = value.id;
                // this.dataSourceBom = this.dataSourceBom.filter(b => b.bomId != bomId);//防止重新选择相同的bom版本，数据叠加重复
                this.getBomDetails(bomId, target.baseQuantity, value.id);
            } else if (dataIndex == 'processRouteName') {
                //工艺路线
                target[dataIndex] = value.name;
                target['processRouteId'] = value.id;

                //加工单获取工艺路线
                if (this.$route.path == '/production/productionWork' || this.$route.path == '/outsource/outProductionWork') {
                    this.getRouteDetails(value.id);
                }
            } else if (dataIndex == 'inventoryCategoryName') {
                //存货分类
                target[dataIndex] = value.name;
                target['inventoryCategoryId'] = value.id;

            } else if (dataIndex == 'workerName') {
                //工人姓名
                target[dataIndex] = value.name;
                target['workerId'] = value.id;
            } else if (dataIndex == 'baseQuantity' || dataIndex == 'price' || dataIndex == 'includeTaxPrice'
                || dataIndex == 'taxRate' || dataIndex == 'unitExchangeRate' || dataIndex == 'subQuantity'
                || dataIndex == 'subUnit' || dataIndex == 'estimatedPrice' || dataIndex == 'estimatedAmount'
                || dataIndex == 'quantity' || dataIndex == 'length' || dataIndex == 'width') {

                /**
                * includeTaxPrice:含税单价
                * baseQuantity:数量
                * taxRate：税率
                * amount:金额
                * includetaxAmount:含税金额
                *
                * unitExchangeRate:换算率
                * subQuantity:辅计量数量
                * estimatedPrice:暂估单价
                * estimatedAmount：暂估金额
                *
                */
                if (target && (value || value == 0)) {

                    //辅助计量改变的时候 换算率赋值后也要计算 dataIndex == 'subUnit'
                    if (dataIndex != 'subUnit') {
                        target[dataIndex] = value;
                    } else {
                        //console.log('辅计量选中的值---------', value)
                        target['subUnit'] = value.name;
                        target['subUnit_temp_id'] = value.id;//辅计量id
                        target['subUnitName'] = value.name;
                        target['unitExchangeRate'] = value.unitExchangeRate;  //换算率
                    }


                    //面积计算表 计算面积
                    if (target.quantity && target.unitArea) {
                        target['totalArea'] = (target.quantity * target.unitArea).toFixed(4);
                    }
                    if (target.length && target.width) {
                        target['unitArea'] = (Number(target.length) * Number(target.width)).toFixed(4);
                    }

                    //==========================换算率相关

                    //输入换算率的时候
                    if (dataIndex == 'unitExchangeRate' || value.unitExchangeRate) {
                        //辅计量必须选择
                        if (!target.subUnit || target.subUnit == null || target.subUnit == '' || !target.subQuantity) {
                            this.$message.error('辅计量 和 辅计量数量 必须存在值');
                            return;
                        } else {
                            if (target.baseQuantity) {
                                target['subQuantity'] = '';
                                //辅计量数量=主计量数量 / 换算率
                                let n = Number(target.baseQuantity) / Number(target.unitExchangeRate);
                                target['subQuantity'] = n.toFixed(4);
                            }
                        }
                    }

                    //输入辅计量数量的时候
                    if (dataIndex == 'subQuantity') {
                        //辅计量必须选择
                        if (!target.subUnit || target.subUnit == null || target.subUnit == '') {
                            this.$message.error('辅计量必须选择');
                            return;
                        } else {
                            // if (target.baseQuantity) {
                            //     //换算率 = 主计量数量/辅计量数量
                            //     let n = Number(target.baseQuantity) / Number(target.subQuantity);
                            //     target['unitExchangeRate'] = n.toFixed(4);
                            // } else {
                            //主计量数量 = 辅计量数量*换算率
                            let n = Number(target.subQuantity) * Number(target.unitExchangeRate);
                            target['baseQuantity'] = n.toFixed(4);
                            // }
                        }
                    }
                    //输入数量的时候
                    if (dataIndex == 'baseQuantity') {
                        //输入数量  并且辅计量数量存在
                        if (target.unitExchangeRate) {
                            //辅计量数量 = 主计量数量/换算率
                            let total = Number(target.baseQuantity) / Number(target.unitExchangeRate);
                            target['subQuantity'] = total.toFixed(4);
                        }
                        //输入数量 并且暂估单价存在
                        if (target.estimatedPrice) {
                            target['estimatedAmount'] = (target.baseQuantity * target.estimatedPrice).toFixed(2);
                        } else if (target.estimatedAmount) {
                            target['estimatedPrice'] = (target.estimatedAmount / target.baseQuantity).toFixed(2);
                        }
                    }

                    //暂估单价
                    if (dataIndex == 'estimatedPrice') {
                        if (target.baseQuantity) {
                            target[dataIndex] = value;
                            target['estimatedAmount'] = (target.baseQuantity * target.estimatedPrice).toFixed(2);
                        }
                    }
                    //暂估金额
                    if (dataIndex == 'estimatedAmount') {
                        if (target.baseQuantity) {
                            target[dataIndex] = value;
                            target['estimatedPrice'] = (target.estimatedAmount / target.baseQuantity).toFixed(2);
                        }
                    }


                    //☆☆☆☆☆☆☆触发委外加工单物料数量的计算☆☆☆☆☆☆☆
                    if (dataIndex == 'baseQuantity' || dataIndex == 'unitExchangeRate' || dataIndex == 'subQuantity')
                        if ((this.sourceCode == 'DelegateProductionWork' || this.sourceCode == 'ProductionWork') && this.dataSourceBom) {//页面如果是委外加工单和加工单
                            if (this.dataSourceBom.length > 0) {//判断物料明细是否有数据
                                this.dataSourceBomNumber = Number(target.baseQuantity);
                                this.dataSourceBom.forEach(item => {

                                    //         if (item.bomId == this.classWorkCurrent) {//子件和母件bomid一致时修改
                                    let num = Number(target.baseQuantity) * Number(item.baseRequireQuantity);
                                    item.requireQuantity = num;
                                    //         }

                                });
                            }
                        }

                    //==========================换算率相关

                    //计算单价
                    if (dataIndex == 'includeTaxPrice') {
                        target['price'] = '';
                        if (target.includeTaxPrice && target.taxRate && target.baseQuantity) {
                            //1.计算 含税金额
                            let includeTaxAmount = Number(target.includeTaxPrice) * Number(target.baseQuantity);
                            //2.通过 含税金额 计算 金额
                            let amount = includeTaxAmount / (1 + target.taxRate / 100);
                            //3.单价 = 金额 / 数量
                            let price = amount / Number(target.baseQuantity);
                            target['price'] = price.toFixed(2);
                            // let total = Number(target.includeTaxPrice) / (1 + target.taxRate / 100);
                            // target['price'] = total.toFixed(2);

                            //includeTaxPrice
                            //价税合计 含税金额*数量
                            target['taxAmount'] = target.tax;//税额

                            target['priceTaxTotal'] = (Number(target.includeTaxPrice) * Number(target.baseQuantity)).toFixed(2);//价税合计
                        } else {
                            target['price'] = (Number(target.includeTaxPrice) / (1 + (target.taxRate || 0) / 100)).toFixed(2);
                        }
                    }
                    //计算含税单价
                    if (dataIndex == 'price' || dataIndex == 'baseQuantity') {
                        // target['includeTaxPrice'] = '';

                        if (target.price && target.taxRate) {
                            let total = Number(target.price) * (1 + target.taxRate / 100);
                            target['includeTaxPrice'] = total.toFixed(2);
                        } else if (target.price) {
                            target['includeTaxPrice'] = Number(target.price);
                        }

                        if (target.baseQuantity && target.price) {
                            target['amount'] = (target.baseQuantity * target.price).toFixed(2);
                        }
                    }

                    if (dataIndex == 'taxRate') {//输入税率的情况
                        if (!target.price && !target.includeTaxPrice) {//1.单价和含税单价都不存在
                            return;
                        } else {//两个都存在（以单价为准）
                            target['includeTaxPrice'] = '';//清空含税单价
                            if (target.price && target.taxRate) {
                                let total = Number(target.price) * (1 + target.taxRate / 100);
                                target['includeTaxPrice'] = total.toFixed(2);
                            } else {
                                target['includeTaxPrice'] = Number(target.price);
                            }
                        }
                    }

                    //算税额
                    if (target.baseQuantity && target.price && target.taxRate) {
                        //税率= 单价*数量*税率
                        let tax = Number(target.baseQuantity) * Number(target.price) * Number(target.taxRate) / 100
                        target['tax'] = tax.toFixed(4);
                    }

                    if ((target.baseQuantity || target.baseQuantity == 0) && (target.price || target.price == 0)) {
                        //数量*单价=金额
                        let total = Number(target.baseQuantity) * Number(target.price);
                        target['amount'] = total.toFixed(2);
                    }

                    if (target.baseQuantity && target.includeTaxPrice) {
                        //数量*含税单价=含税金额
                        let total = Number(target.baseQuantity) * Number(target.includeTaxPrice);
                        target['includeTaxAmount'] = total.toFixed(2);
                    }

                    if (target.baseQuantity && target.price) {
                        //算金额
                        target['amount'] = (target.baseQuantity * target.price).toFixed(2);
                    }


                    if (target.includeTaxPrice && target.taxRate && target.baseQuantity) {
                        //1.计算 含税金额
                        let includeTaxAmount = Number(target.includeTaxPrice) * Number(target.baseQuantity);
                        //2.通过 含税金额 计算 金额
                        let amount = includeTaxAmount / (1 + target.taxRate / 100);
                        //3.单价 = 金额 / 数量
                        let price = amount / Number(target.baseQuantity);
                        target['price'] = price.toFixed(2);
                        // let total = Number(target.includeTaxPrice) / (1 + target.taxRate / 100);
                        // target['price'] = total.toFixed(2);

                        //includeTaxPrice
                        //价税合计 含税金额*数量
                        target['taxAmount'] = target.tax;//税额
                        target['priceTaxTotal'] = (Number(target.includeTaxPrice) * Number(target.baseQuantity)).toFixed(2);//价税合计
                    }

                    // if (target.amount && target.tax) {
                    //     //含税金额 = 金额 + 税额
                    //     let total = Number(target.amount) + Number(target.tax);
                    //     target['includeTaxAmount'] = total.toFixed(2);
                    // }
                }
                // } else if (value && (value.columnType == '日期' || value && value.columnType == '起止日期')) {
            } else if (value && value.columnType == '日期') {
                if (target) {
                    target[dataIndex] = value.value;
                }
            } else if (value && value.columnType == '下拉选择') {
                if (target) {
                    target[dataIndex] = value.name;
                    target[dataIndex + 'Id'] = value.id;
                }
            } else if (value && value.columnType == '下拉多选') {
                if (target) {
                    target[dataIndex] = value.key;
                }
            } else if (value && value.columnType == '复选') {
                if (target) {
                    target[dataIndex] = value.val ? '是' : '否';
                }
            } else {
                if (target) {
                    this.$nextTick(() => {
                        target[dataIndex] = value;
                    });
                    this.reload();
                }
            }
            //console.log(this.routePath, 'routePathroutePathroutePathroutePathroutePath')
            if (this.routePath == '/procurement/purchaseRequisition' && value.columnType == '日期') {
                // dataSource.forEach(item => {
                target[dataIndex] = value.value || dataSource[0].planBeginDate
                // })
            }
            this.$nextTick(() => {
                // if (this.routePath  == '/procurement/purchaseRequisition') {
                //     dataSource.forEach(item => {
                //         item.acceptDate = item.planBeginDate
                //     })
                // }
                this.dataSource = dataSource;
                this.reload();
            });
            //修改数据后刷新合计
            if (!this.isAreaX) {
                this.totalCalculate();
            }
        },
        showDrawer() {
            //右侧搜索抽屉
            this.$refs.searchList.onOpen(this.sourceCode)
        },


        //=============================== 表头的搜索选择 ==========================
        setValue(data) {
            const { orderHeaderData } = this;

            if (data.codesName == 'warehouseId' && !orderHeaderData.some(e => e.code == 'warehouseCode')) {
                orderHeaderData.push({
                    code: "warehouseCode",
                    columnType: "文本",
                    name: '仓库编码',
                    dataType: 1,
                    onEdit: false,
                    onFill: true,
                    onOff: true,
                    value: data.whCode,
                    valueName: data.whCode,
                });

            }

            if (data.codesName == 'warehouseId') {
                this.newWarehouseId = data.id;
                //获取该仓库下物料的可用量
                let intoryIds = this.dataSource.map(res => {
                    return { id: res.inventoryId }
                })
                let ids = _.map(intoryIds, 'id').filter(res => res);
                if (ids.length > 0) {
                    this.getNowQuantityFun(ids, data.id, true)
                }
                this.$store.commit('SET_WHEREHOUSEID', data.id)
            }
            if (data.codesName == 'inWarehouseId') {
                this.warehouse.inWarehouseId = data.id;
            }
            if (data.codesName == 'outWarehouseId') {
                this.warehouse.outWarehouseId = data.id;
            }
            if (data.codesName == 'contractTypeId') {
                //合同类型
                this.contractTypeId = data.id;
                this.getCode();
            }

            for (let i = 0; i < orderHeaderData.length; i++) {
                let headerCode = orderHeaderData[i].code;
                if (orderHeaderData[i].code == data.codesName) {
                    //console.log('partnerId:', orderHeaderData[i].code)
                    this.$set(orderHeaderData[i], 'value', data.name)
                    this.$set(orderHeaderData[i], 'valueId', data.id)
                    this.$set(orderHeaderData[i], 'valueName', data.name)
                    this.$forceUpdate();
                }

                if (data.codesName == 'contractTypeId' && orderHeaderData[i].code == 'planDirection') {
                    //合同类型  带出 收付款方向
                    this.$set(orderHeaderData[i], 'valueName', data.planDirection)
                    this.$set(orderHeaderData[i], 'value', data.planDirection);

                }

                if (data.codesName == 'projectId' && orderHeaderData[i].code == 'projectNo') {
                    //项目  带出 项目编码
                    this.$set(orderHeaderData[i], 'valueName', data.code)
                    this.$set(orderHeaderData[i], 'value', data.code);

                }

                if (data.codesName == 'projectId' && orderHeaderData[i].code == 'projectCode') {
                    //项目  带出 项目编码(面积计算表 专属)
                    this.$set(orderHeaderData[i], 'valueName', data.code)
                    this.$set(orderHeaderData[i], 'value', data.code);

                }


                if (data.codesName == 'purchaseTypeId' && orderHeaderData[i].code == 'purchaseTypeCode') {
                    //选择采购类型 带出 采购类型编码
                    this.$set(orderHeaderData[i], 'valueName', data.code)
                    this.$set(orderHeaderData[i], 'value', data.code);

                }

                if (data.codesName == 'accountingId' && orderHeaderData[i].code == 'accountingCode') {
                    //科目名称，科目编码
                    this.$set(orderHeaderData[i], 'valueName', data.code)
                    this.$set(orderHeaderData[i], 'value', data.code);

                }

                if (data.codesName == 'purchaseTypeId' && orderHeaderData[i].code == 'rdStyleId') {
                    //选择采购类型 带出 入库类别
                    this.$set(orderHeaderData[i], 'value', data.styleName)
                    this.$set(orderHeaderData[i], 'valueId', data.styleId);
                    this.$set(orderHeaderData[i], 'valueName', data.styleName)
                }

                if (data.codesName == 'purchaseTypeId' && orderHeaderData[i].code == 'saleTypeCode') {
                    //选择销售类型 带出 销售类型编码
                    this.$set(orderHeaderData[i], 'valueName', data.code)
                    this.$set(orderHeaderData[i], 'value', data.code);
                }

                if (data.codesName == 'saleTypeId' && orderHeaderData[i].code == 'rdStyleId') {
                    //选择销售类型 带出 出库类别
                    this.$set(orderHeaderData[i], 'value', data.styleName)
                    this.$set(orderHeaderData[i], 'valueId', data.styleId);
                    this.$set(orderHeaderData[i], 'valueName', data.styleName)
                }

                if (data.codesName == 'warehouseId' && orderHeaderData[i].code == 'warehouseCode') {
                    //仓库编码
                    this.$set(orderHeaderData[i], 'valueName', data.whCode)
                    this.$set(orderHeaderData[i], 'value', data.whCode)
                }

                if (data.codesName == 'productId' || data.codesName == 'inventoryId') {
                    if (headerCode == 'productCode') {
                        //选择加工产品名称 带出 加工产品编码
                        this.$set(orderHeaderData[i], 'valueName', data.inventoryCode)
                        this.$set(orderHeaderData[i], 'value', data.inventoryCode)
                    } else if (headerCode == 'inventorySpecification') {
                        //带出规格型号
                        this.$set(orderHeaderData[i], 'valueName', data.inventorySpecification)
                        this.$set(orderHeaderData[i], 'value', data.inventorySpecification)
                    } else if (headerCode == 'inventoryDescript') {
                        //带出规格型号
                        this.$set(orderHeaderData[i], 'valueName', data.inventoryDescript)
                        this.$set(orderHeaderData[i], 'value', data.inventoryDescript)
                    }
                }
            }
            Object.assign(this.orderHeaderData, orderHeaderData)
            //改变 发票表单  的标题颜色
            if ((this.$route.path == '/procurement/purchaseInvoice' || this.$route.path == '/sale/saleInvoice') && data.codesName == 'invoiceTypeId') {
                //记录选中的 发票类型
                this.recordInvoiceType = data.type;

                if (data.type == 0) {
                    document.querySelectorAll("h2.text-center")[0].style.color = 'red'
                } else {
                    document.querySelectorAll("h2.text-center")[0].style.color = 'rgba(0,0,0,.85)'
                }
            }
            // 查询 表头选中 的工艺路线 的明细列表
            if (this.sourceCode == 'ProcedurePrice' && data.codesName == 'processRouteId') {
                this.detailsRouteForProcedurePrice(data.id);
            }

        },
        onChangeTime(backData) {
            let { dateString, code } = backData;
            let { dynamicFormDataMap } = this;
            let formData = dynamicFormDataMap.get(code);
            //console.log("表头/表尾选择日期：", dateString, code, formData);
            this.$set(formData, 'value', dateString);
            //console.log(this.orderHeaderData);
            //console.log(this.orderFooterData);
            //日期修改
            // const { orderHeaderData } = this;
            // for (let i = 0; i < orderHeaderData.length; i++) {
            //     if (orderHeaderData[i].code == backData.code) {
            //         this.$set(orderHeaderData[i], 'value', backData.dateString)
            //     }
            // }
            // Object.assign(this.orderHeaderData, orderHeaderData)
        },
        deleteOrder(type) {
            //删除
            let _this = this;
            let postData = {
                id: this.orderId
            };
            if (type=='mrp') {
                if (_this.orderId) {
                    _this.$confirm({
                        title: "确认",
                        content: (
                            <span>
                                您确定要{<span style="color:red;">删除</span>}该张单据吗？
                            </span>
                        ),
                        onOk() {
                            _this.mapRemove(postData);
                        },
                        onCancel() { },
                    });
                }
            } else {
                if (_this.orderId) {
                    _this.$confirm({
                        title: "确认",
                        content: (
                            <span>
                                您确定要{<span style="color:red;">删除</span>}该张单据吗？
                            </span>
                        ),
                        onOk() {
                            _this.remove(postData);
                        },
                        onCancel() { },
                    });
                }
            }
        },
        clickEdit() {
            //修改 关闭遮罩层
            this.editMask = false;
        },
        printOrder() {
            //打印
            // this.$print(this.$refs.print);
            //console.log(this.columns, this.dataSource)
            this.incomingPrintData = {
                title: this.voucherTitle,//单据名称
                orderDetailData: this.orderDetailData,
                orderHeaderData: this.orderHeaderData,
                orderFooterData: this.orderFooterData,
                data: this.dataSource,
            };
            this.printVisible = true;
            this.$nextTick(() => {
                this.$refs.printDom.showModal();
            })
        },
        cancelPrint() {
            this.printVisible = false;
        },
        totalCalculate() {

            //合计计算
            let includeTaxAmountTotal = 0;  //含税金额总价
            let amountTotal = 0;            //金额总价
            let taxTotal = 0;                 //税额
            // let baseQuantityTotal = 0;        //数量
            let shouldAmountTotal = 0;         //应收金额

            let priceTaxTotalAll = 0;       //价税合计
            //console.log('amountTotal:', this.dataSource)
            this.$nextTick(() => {
                for (let i = 0; i < this.dataSource.length; i++) {
                    if ((this.dataSource[i].inventoryId || this.dataSource[i].amount || this.dataSource[i].amount == 0 || this.dataSource[i].amount == null) && this.dataSource[i].name != 'total') {
                        includeTaxAmountTotal += Number(this.dataSource[i].includeTaxAmount ? this.dataSource[i].includeTaxAmount : 0);
                        amountTotal += Number(this.dataSource[i].amount ? this.dataSource[i].amount : 0);
                        taxTotal += Number(this.dataSource[i].tax ? this.dataSource[i].tax : 0);
                        // baseQuantityTotal += Number(this.dataSource[i].baseQuantity ? this.dataSource[i].baseQuantity : 0);
                        priceTaxTotalAll += Number(this.dataSource[i].priceTaxTotal ? this.dataSource[i].priceTaxTotal : 0);
                        if (this.dataSource[i].shouldAmount) {
                            //应收金额
                            shouldAmountTotal += Number(this.dataSource[i].shouldAmount ? this.dataSource[i].shouldAmount : 0);

                        }
                    }
                    if (this.dataSource[i].name == 'total') {
                        this.dataSource[i].includeTaxAmount = includeTaxAmountTotal.toFixed(2);
                        this.dataSource[i].amount = amountTotal.toFixed(2);
                        this.dataSource[i].tax = taxTotal.toFixed(2);
                        this.dataSource[i].priceTaxTotal = priceTaxTotalAll.toFixed(2);
                        // this.$set(this.dataSource[i], 'baseQuantity', baseQuantityTotal.toFixed(2));
                        if (shouldAmountTotal > 0) {
                            //应收金额
                            this.$set(this.dataSource[i], 'shouldAmount', shouldAmountTotal.toFixed(2));
                        }
                    }
                }
                //---财务应收应付表头计算金额----
                this.orderHeaderData.forEach(item => {
                    if (item.code == 'amount') {
                        this.$set(item, 'value', amountTotal.toFixed(2))
                        this.$set(item, 'valueName', amountTotal.toFixed(2))
                    }
                    if (item.code == 'shouldAmount') {
                        this.$set(item, 'value', shouldAmountTotal.toFixed(2))
                        this.$set(item, 'valueName', shouldAmountTotal.toFixed(2))
                    }
                    if (item.code == 'tax') {
                        this.$set(item, 'value', taxTotal.toFixed(4))
                        this.$set(item, 'valueName', taxTotal.toFixed(4))
                    }

                    if (item.code == 'priceTaxTotal') {
                        this.$set(item, 'value', (Number(taxTotal) + Number(amountTotal)).toFixed(2))
                        this.$set(item, 'valueName', (Number(taxTotal) + Number(amountTotal)).toFixed(2))
                    }
                    if (item.code == 'contractPrice') {
                        //合同金额  就是  合同明细的价税合计
                        this.$set(item, 'value', priceTaxTotalAll.toFixed(2))
                        this.$set(item, 'valueName', priceTaxTotalAll.toFixed(2))
                    }

                });
                this.reload();
            })

        },
        //=============================== 表头的搜索选择 ==========================

        //=============================== 右键（新增，删除，修改） ==========================
        openMenu(e) {
            //显示右键菜单
            var x = e.pageX - 250;
            var y = e.pageY - 40;
            this.top = y;
            this.left = x;
            this.visible = true;
        },
        closeMenu() {
            //隐藏右键菜单
            this.visible = false;
        },
        handleAdd() {
            //新增数据
            const { count, dataSource } = this;
            const newData = {
                number: count,
            };
            this.$nextTick(() => {
                this.dataSource.splice(this.dataSource.length - 1, 0, newData);
                // this.$refs.print.scrollTo(0, 500)
                // document.getElementsByClassName('documents-wrapper').scroll(0, 500)
                document.getElementById('documents-wrapper').scroll(0, this.$refs.print.scrollHeight)
                this.reload();
            })
        },
        handleDelete() {
            //删除整行
            let _this = this;
            let numberId = this.thisClickId;
            this.$confirm({
                title: "确认",
                content: (
                    <span>
                        您确定要{<span style="color:red;">删除</span>}该记录吗？
                    </span>
                ),
                onOk() {
                    let dataSource = [..._this.dataSource];

                    if (_this.sourceCode == 'ProductionWork' || _this.sourceCode == 'DelegateProductionWork') {
                        //获取当前记录的bomId
                        // let deleteRow = dataSource[numberId];
                        // console.log("删除行数据", deleteRow)
                        // if (deleteRow.bomId) {
                        //     _this.dataSourceBom = _this.dataSourceBom.filter(b => b.bomId != deleteRow.bomId);//删除对应的材料明细
                        // }

                    }
                    _this.dataSource = dataSource.filter((item, index) => index !== numberId);
                    if (_this.dataSource.length < _this.dataSourceNumber + 1) {
                        _this.dataSource.push({});
                    }
                    // else {
                    //     //小于规定行数(清空)
                    //     for (let i = 0; i < dataSource.length; i++) {
                    //         if (i === numberId) {
                    //             for (const key in dataSource[i]) {
                    //                 if (key != 'number') {
                    //                     dataSource[i][key] = null;
                    //                 }
                    //             }
                    //         }
                    //     }
                    //     _this.dataSource = dataSource;
                    // }


                    _this.totalCalculate();//重新计算

                    _this.reload();
                },
                onCancel() { },
            });
        },
        handleCopy() {
            //复制行
            const { count, dataSource, thisClickRecord } = this;
            if (!thisClickRecord.inventoryCode) {
                this.$message.warning('复制数据不存在', 1)
                return;
            }
            // this.dataSource = [...dataSource, newData];
            let nowData = { ...thisClickRecord };
            // nowData.number = count;
            nowData.id = '';
            newData.orderId = '';
            newData.sourceVoucherCode = '';
            newData.sourceVoucherDate = '';
            newData.sourceVoucherId = '';
            newData.sourceVoucherType = '';

            this.dataSource.splice(this.thisClickId + 1, 0, nowData);
            this.reload();
        },
        //物料多选
        choiceAddData(index,dataIndex, record) {
            let newData = _.cloneDeep(record);
            let runAddDataSource = true;

            //判断列表中是否存在该物料（加工单 和 委外加工单 物料不能重复）
            if (this.$route.path == '/production/productionWork' || this.$route.path == '/outsource/outProductionWork') {
                for (let i = 0; i < newData.length; i++) {
                    for (let k = 0; k < this.dataSource.length; k++) {
                        if (this.dataSource[k].inventoryId == (newData[i].inventoryId || newData[i].id)) {
                            this.$message.warning('物料已经存在当前单据,不能重复添加', 1);
                            runAddDataSource = false;
                            break;
                        }
                    }
                }
            }

            // MRP运算
            if (this.$route.path == '/procurement/purchaseReceipt') {
                const computedData =  [...this.computedData];
                const target = computedData.find((item, indexKey) => indexKey === index);
                const newObj = record[0]
                this.$set(target, dataIndex, newObj)
                this.editMask = false
                this.voucherState = -1
                if (dataIndex == 'workCode' || dataIndex == 'workName') {
                    //工序编码
                    if (newObj) {
                        target['workCode'] = newObj.code;
                        target['workId'] = newObj.id;
                        target['workName'] = newObj.name;
                        target['processMethod'] = newObj.processMethod;
                    } else {
                        target['workCode'] = null;
                        target['workId'] = null;
                        target['workName'] = null;
                        target['processMethod'] = null;
                    }

                } else if (dataIndex == 'inventoryCode' || dataIndex == 'inventoryName') {
                    //子件编码
                    if (newObj) {
                        target['inventoryCode'] = newObj.inventoryCode;
                        target['inventoryId'] = newObj.id;
                        target['inventoryName'] = newObj.inventoryName;
                        target['specification'] = newObj.inventorySpecification;
                        target['unitName'] = newObj.unitName ? newObj.unitName : newObj.unitGroupName;
                        target['unitId'] = newObj.unitId ? newObj.unitId : newObj.unitGroupId;

                        //置空当前子件数据
                        target['bomVersion'] = null;
                        target['bomId'] = null;
                        target['requireQuantity'] = null;
                        target['remarks'] = null;
                        target['supplyType'] = null;

                    } else {
                        target['inventoryCode'] = null;
                        target['inventoryId'] = null;
                        target['inventoryName'] = null;
                        target['specification'] = null;
                        target['unitName'] = null;
                        target['unitId'] = null;
                    }
                } else if (dataIndex == 'bomVersion') {
                    //查询下级bom(子件bom)
                    if (newObj) {
                        target['bomVersion'] = newObj.versionCode;
                        target['bomId'] = newObj.id;
                    } else {
                        target['bomVersion'] = null;
                        target['bomId'] = null;
                    }
                } else if (dataIndex == 'adjustProportion' || dataIndex == 'adjustNumber' || dataIndex == 'operationQuantity') {
                    //调整比例，调整数量，运算数量
                    if (dataIndex == 'adjustProportion') {
                        if (newObj) {
                            //运算数量=数量 *（调整比例/100）
                            target['adjustNumber'] = (Number(target.baseQuantity) * (newObj.baseQuantity / 100)).toFixed(2);
                            target['operationQuantity'] = (Number(target['adjustNumber']) + Number(target.baseQuantity)).toFixed(2);
                        }
                    }
                    if (dataIndex == 'adjustNumber') {
                        if (newObj) {
                            //调整比例=数量/调整数量 * 100
                            target['adjustProportion'] = (newObj.baseQuantity / Number(target.baseQuantity) * 100).toFixed(2);
                            target['operationQuantity'] = (Number(target['adjustNumber']) + Number(target.baseQuantity)).toFixed(2);
                        }
                    }

                    if (dataIndex == 'operationQuantity') {
                        if (newObj) {
                            //调整比例=数量/调整数量* 100
                            target['adjustNumber'] = (newObj.baseQuantity - Number(target.baseQuantity)).toFixed(2);
                            target['adjustProportion'] = ((target['adjustNumber'] / Number(target.baseQuantity)) * 100).toFixed(2);
                        }
                    }

                } else {
                    this.$nextTick(() => {
                        target[dataIndex] = newObj;
                    });
                }
            }

            if (record[0].specialGw == true) {
                let produ = {};
                // this.dataSource[index].splice(index, 1, produ);
                this.dataSource.forEach((item, i) => {
                    if (i == index) {
                        item['productCode'] = record[0].inventoryCode; //对应产品编码
                        item['productId'] = record[0].id;            //对应产品名称
                        item['productName'] = record[0].inventoryName; //对应产品名称
                    }
                });
            } else {
                //去除 当前记录 其他字段信息
                this.dataSource.forEach((item, i) => {
                    if (i == index) {
                        for (const key in item) {
                            if (key != 'warehouseName' && key != 'warehouseId' && key != 'warehouseCode') {
                                item[key] = ''
                            }
                        }
                    }
                });
                if (runAddDataSource) {
                    for (let i = 0; i < newData.length; i++) {
                        let newDetails = {};
                        if (newData.length == 1) {
                            this.dataSource.forEach((item, i) => {
                                if (i == index) {
                                    newDetails = item;
                                }
                            });
                        }
                        newDetails['releaseState'] = "未下达"; //下达状态
                        newDetails['inventoryCode'] = newData[i].inventoryCode;//物料编码
                        newDetails['inventoryId'] = newData[i].id;//物料名称
                        newDetails['inventoryName'] = newData[i].inventoryName;//物料名称
                        newDetails['inventorySpecification'] = newData[i].inventorySpecification;//规格型号
                        newDetails['inventoryDescript'] = newData[i].inventoryDescript;//规格型号
                        newDetails['taxRate'] = newData[i].taxRate ? newData[i].taxRate : 0;//税率
                        //含税单价 赋值

                        if (this.saleVoucherArr.includes(this.sourceCode)) {
                            //   alert("sourceCode:"+this.sourceCode+",售价：")
                            newDetails.includeTaxPrice = newData[i].sellingPrice || newData[i].refSellingPrice || newData[i].minSellingPrice || 0.00;
                        } else {
                            // alert("sourceCode:"+this.sourceCode+",成本价：")
                            newDetails.includeTaxPrice = newData[i].latestCost ? newData[i].latestCost : newData[i].referenceCost ? newData[i].referenceCost : 0.00;//单价（最新成本or参考成本）
                        }
                        //计算 单价
                        newDetails['price'] = (Number(newDetails.includeTaxPrice) / (1 + (newDetails.taxRate || 0) / 100)).toFixed(2);
                        newDetails['inventoryCategoryName'] = newData[i].inventoryCategoryName;//存货分类
                        newDetails['inventoryCategoryId'] = newData[i].inventoryCategoryId;//存货分类id

                        //处理库存初期，仓库
                        this.orderHeaderData.forEach(element => {
                            if (element.code == 'warehouseId') {
                                newDetails['warehouseId'] = element.valueId;
                                newDetails['warehouseName'] = element.valueName;
                            }
                        });


                        if (newData[i].unitType == '单计量') {
                            newDetails['baseUnit'] = newData[i].unitName;
                            newDetails['baseUnitName'] = newData[i].unitName;
                            newDetails['baseUnit_temp_id'] = newData[i].unitId;

                            newDetails['unitId'] = newData[i].unitId;//用于区分返回值 是否是单计量
                        } else {
                            let mainId = null;//主计量id

                            newDetails['baseUnit'] = newData[i].mainUnitName;
                            newDetails['baseUnitName'] = newData[i].mainUnitName;
                            newDetails['baseUnit_temp_id'] = newData[i].mainUnit;

                            newDetails['unitGroupId'] = newData[i].unitGroupId; //用于区分返回值是否是多计量

                            mainId = newData[i].unitGroupId;

                            // for (let j = 0; j < this.unitsDataDetails.length; j++) {
                            //     if (this.unitsDataDetails[j].id == newData[i].mainUnit) {
                            //         newDetails['baseUnit'] = this.unitsDataDetails[j].name;//主计量
                            //         newDetails['baseUnitName'] = this.unitsDataDetails[j].name;//主计量
                            //         newDetails['baseUnit_temp_id'] = this.unitsDataDetails[j].id;//主计量id
                            //         newDetails['baseUnitId'] = this.unitsDataDetails[j].id;
                            //         newDetails['unitGroupId'] = this.unitsDataDetails[j].id;
                            //         mainId = this.unitsDataDetails[j].unitGroupId;
                            //     }
                            // }

                            //辅助计量数据
                            let unitsAssistSelect = [];
                            this.unitsDataDetails.forEach(item => {
                                if (item.unitGroupId == mainId && !item.isMainUnit) {// && !item.isMainUnit
                                    unitsAssistSelect.push(item);
                                }
                            });

                            // console.log('多选-》》》》》》辅助计量组：', unitsAssistSelect, this.unitsDataDetails, mainId)

                            unitsAssistSelect.forEach(item => {
                                //(采购)
                                if (this.sourceCode == 'PurchaseRequisition' || this.sourceCode == 'PurchaseOrder' || this.sourceCode == 'PuArrival' || this.sourceCode == 'PurchaseInvoice' || this.sourceCode == 'PurchaseReceiveVoucher') {
                                    if (item.id == newData[i].purUnit) {
                                        newDetails['subUnit'] = item.name;
                                        newDetails['subUnit_temp_id'] = item.id;
                                        newDetails['subUnitName'] = item.name;
                                        newDetails['unitExchangeRate'] = item.changeRate;  //换算率
                                    }
                                } else {
                                    //(销售和其他)
                                    if (item.id == newData[i].saleUnit) {
                                        newDetails['subUnit'] = item.name;
                                        newDetails['subUnit_temp_id'] = item.id;
                                        newDetails['subUnitName'] = item.name;
                                        newDetails['unitExchangeRate'] = item.changeRate;  //换算率
                                    }
                                }
                            });
                        }

                        if (newData.length == 1) {
                            this.dataSource.splice(index + i, 1, newDetails);
                        } else {
                            this.dataSource.splice(index + i, 0, newDetails);
                        }

                    }
                }
            }

            //获取该仓库下物料的可用量
            let intoryIds = this.dataSource.map(res => {
                return { id: res.inventoryId }
            })
            let ids = _.map(intoryIds, 'id').filter(res => res);
            this.getNowQuantityFun(ids, this.newWarehouseId);

            this.reload();
        },
        //=============================== 右键（新增，删除，修改） ==========================



        //=============================== 翻页 ==========================
        turnThePage(turnpage) {
            let { basePostData } = this;
            this.loading = true;
            let postData = {
                currentId: this.orderId,
                source: this.sourceCode,
                actionType: turnpage,//1:上一页 2：下一页 3：首页 4：尾页
            }
            if (this.$route.path == '/production/management/productionOrder') {
                postData.source = 'RequirementPlan'
            }
            Object.assign(postData, basePostData);
            getbyid(postData).then((response) => {
                if (response.code === 200) {
                    const backData = response.data;
                    this.orderData = response.data;
                    if (backData) {
                        if (!backData.voucherState) {
                            this.$set(backData, 'voucherState', 0)
                        }
                        this.editMask = true;   //开启遮罩
                        this.orderId = backData.id;
                        this.$route.query.id = this.orderId;//给路由赋值
                        if (this.sourceCode == 'ReceivableVoucher' || this.sourceCode == 'PayableVoucher') {
                            //财务应收应付 获取收款计划 和 付款计划
                            this.getlistInPlan()
                        }
                        setTimeout(() => {
                            this.editClickOrder(backData);
                        }, 500)


                        //新西亚 面积计算表 获取出入库数量
                        if (this.areaInOut && this.orderData.id) {
                            setTimeout(() => {
                                this.getInOutRecord();
                            }, 1000)
                        }

                    } else {
                        if (turnpage == 1 || turnpage == 3) {
                            this.loading = false;
                            this.$message.destroy();
                            this.$message.warning('已经是首页了');
                        } else {
                            this.loading = false;
                            this.$message.destroy();
                            this.$message.warning('已经是尾页了');
                        }
                        setTimeout(() => {
                            this.$message.destroy();
                        }, 800)
                    }
                } else {
                    // this.$message.warning(res.message);
                }
            })
        },
        //=============================== 翻页 ==========================



        //获取最新一条数据
        getIdByData(currentId, source) {
            // this.$route.query.id = currentId;//给路由赋值
            // console.log("从列表 传入currentId ", currentId,)
            this.editMask = true;   //开启遮罩
            let { basePostData } = this;
            let defaultPageData = {
                currentId: currentId || this.orderId,
                source: this.sourceCode,
            }
            if (this.$route.path == '/production/management/productionOrder') {
                defaultPageData = {
                    currentId: '',
                    source: 'RequirementPlan'
                }
            }
            Object.assign(defaultPageData, basePostData);
            if (source == 'transfers') {
                //调拨单退单
                defaultPageData.currentId = null;
                defaultPageData.actionType = 4;  //4：尾页
            }

            if (this.$route.path == '/inventory/transfers/transfers') {
                //调拨单
                defaultPageData.startVoucherState = 1;
            }
            if (defaultPageData.source == 'MrpOperation') {
                //调拨单
                defaultPageData = {
                    currentId: '',
                    source: 'MrpOperation'
                }
            }
            if (defaultPageData.source == 'ProductionOrder') {
                defaultPageData.source = 'MasterProductionSchedule'
            }
            if (Object.keys(this.invoiceData).length > 0) {
                // this.initForm(2);
                //生单或者选单进入
                setTimeout(() => {
                    if(this.routePath == '/sale/saleOrder'){
                        this.orderData = this.invoiceData;
                        this.orderData.voucherCode = ""
                    }
                    console.log(source);
                    console.log(this.invoiceData);
                    this.getCode();
                    this.editClickOrder(this.invoiceData, 'iscreate');
                }, 500)
            } else {
                //console.log("___BBQ___获取最新一条记录:", defaultPageData)
                // if(this.numbers==4){
                //     console.log('没有请求最新数据哟')
                //     this.getCode();
                // }
                this.loading = true;
                getbyid(defaultPageData).then((response) => {

                    if (response.code === 200) {
                        if(window.location.pathname=='/production/management/productionOrder'){
                            if(this.numbers==4){
                                if(response.data){
                                    let detailList = response.data.detailList.map((element,index)=> {
                                        return {
                                            ...element,
                                            baseUnit : element.baseUnitName,
                                            baseUnitId : element.baseUnit,
                                            baseUnit_temp_id : element.baseUnit,
                                            bussessPlanId : element.bussessPlan,
                                            bussessPlan : element.bussessPlan == 1 ? "采购" : element.bussessPlan == 2 ? "自制" :element.bussessPlan ? "委外" : "",
                                            releaseStateId: element.releaseState ? element.releaseState : "",
                                            releaseState: element.releaseState == 1 ? "未下达" : element.releaseState == 2 ? "部分下达" : element.releaseState ? "全部下达" : "",
                                            operationQuantity: element.baseQuantity,
                                            operationNumber: element.baseQuantity,
                                            number: index + 1
                                        }
                                    });
                                    this.$store.commit('SET_MRP', detailList)
                                    //response.data.detailList = this.$store.state.order.mrpBackData
                                }
                            }
                        }
                        const backData = response.data
                        this.orderData = response.data;
                        if (backData == null) {
                            this.dataSource = []
                            //表示一条数据都没有 去新增
                            this.newForecast();
                        } else if (!defaultPageData.currentId && !backData) {
                            this.dataSource = []
                            //表示一条数据都没有 去新增
                            this.newForecast();
                        } else {
                            if (backData) {
                                this.orderId = backData.id;
                                if (!backData.voucherState) {
                                    this.$set(backData, 'voucherState', 0)
                                }
                                //this.initForm(2);
                                if (this.sourceCode == 'ReceivableVoucher' || this.sourceCode == 'PayableVoucher') {
                                    //财务应收应付 获取收款计划 和 付款计划
                                    this.getlistInPlan()
                                }


                                setTimeout(() => {
                                    if (Object.keys(this.invoiceData).length == 0) {
                                        this.editClickOrder(backData)
                                    }
                                }, 500)


                                //新西亚 面积计算表 获取出入库数量
                                if (this.areaInOut && this.orderData.id) {
                                    setTimeout(() => {
                                        this.getInOutRecord();
                                    }, 1000)
                                }
                            }
                        }
                    } else {
                        // this.$message.warning(res.message);
                    }
                })


            }
        },
        //去除数据中的id
        copyRemoveIdData(data) {
            let backData = JSON.parse(data);
            let details = backData.detailList;
            backData.id = '';
            backData.voucherState = -1;
            //console.log(backData);
            for (const key in details) {
                details[key].id = '';
                details[key].orderId = '';
            }
            return backData;
        },




        //=============================== 选单 ==========================
        choiceBills(source, ischoose, title, businessType, someBusinessType) {
            /**
             * source: 单据类型(来源单据source)
             * ischoose：是否是选单
             * title:抽屉名
             * voucherState==1审核通过，才能选单
             */
            this.$refs.searchList.onOpen(source, ischoose, title, 1, businessType, someBusinessType);
        },
        //=============================== 选单 ==========================



        //=============================== 生单 ==========================
        generateBills(source,n=4,arr=[]) {
            //console.log(arr,'6666')
            if(n==0||n==1||n==2){
                if(arr.length<=0){
                    this.$confirm({
                        title:'提示',
                        content:'请选中一条数据!',
                        onOk() {},
                        onCancel() { }
                    })
                    return
                }else{
                    for(var i=0;i<arr.length;i++){
                        for(var j=i+1;j<arr.length;j++){
                            if(arr[i].bussessPlanId==arr[j].bussessPlanId){
                                //console.log('通过')
                            }else{
                                this.$confirm({
                                    title:'提示',
                                    content:'请选中相同的数据!',
                                    onOk() {},
                                    onCancel() { }
                                })
                                return
                            }
                        }
                    }
                }
            }

            if(n==0||n==1||n==2){
                for( let i = 0 ; i < arr.length ; i++ ) {
                    //计划数量  下达数量
                    if(parseInt(arr[i].baseQuantity) <= parseInt(arr[i].releasedQuantity)){
                        this.$confirm({
                            title:'提示',
                            content:'下达数量小于计划数量时才能下达！',
                            onOk() {},
                            onCancel() { }
                        })
                        return
                    }
                }

            }

            //储存当前页数据(去除id)
            let defaultPageData = {
                currentId: this.orderId,
                source: this.sourceCode,
            }

            if(this.$route.path == '/production/management/productionOrder' && (n == 0 || n == 1 || n == 2)){
                defaultPageData.source = "RequirementPlan"
            }


            // if(this.$route.path == '/production/productionPlan' && (n == 0 || n == 1 || n == 2)){
            //     defaultPageData.currentId = ""
            //     for( let i = 0 ; i < arr.length ; i++ ) {
            //         defaultPageData.currentId += arr[i].id +"" + ","
            //     }
            //     defaultPageData.currentId = defaultPageData.currentId.substring(0,defaultPageData.currentId.length-1)
            // }

            getbyid(defaultPageData).then((response) => {
                console.log(response);
                if (response.code === 200) {
                    const backData = response.data;
                    this.$set(backData, 'generateSourceCode', source);
                    this.$set(backData, 'sourceVoucherId', backData.id);    //来源id
                    this.$set(backData, 'sourceVoucherCode', backData.voucherCode);    //来源单号
                    this.$set(backData, 'sourceVoucherDate', backData.voucherDate);    //来源日期
                    this.$set(backData, 'sourceVoucherType', this.sourceCode);   //来源单据
                    if (backData.contractCode) {
                        //合同来源单号 单独处理
                        this.$set(backData, 'sourceVoucherCode', backData.contractCode);    //来源单号
                    }
                    //明细中添加来源
                    backData.detailList.forEach(element => {
                        this.$set(element, 'sourceVoucherId', backData.id);    //来源id
                        // this.$set(element, 'sourceVoucherId', element.id);    //来源id
                        this.$set(element, 'sourceVoucherCode', backData.voucherCode);    //来源单号
                        if (backData.contractCode) {
                            //合同来源单号 单独处理
                            this.$set(element, 'sourceVoucherCode', backData.contractCode);    //来源单号
                        }
                        this.$set(element, 'sourceVoucherDate', backData.voucherDate);    //来源日期
                        this.$set(element, 'sourceVoucherType', this.sourceCode);   //来源单据
                    });

                    //退货单特殊处理
                    if (source == 1) {
                        //采购退货
                        backData.businessType = 97;
                    } else if (source == 2) {
                        //销售退货单
                        backData.businessType = 98;
                    } else if ("purchaseReturn" == source) {
                        //采购退货(已入库)
                        backData.businessType = 99;
                    }

                    //样品单生成合同
                    if (source == 'Contract') {
                        backData.oppositeCompanyId = backData.crmId;
                        backData.oppositeCompanyName = backData.crmName;
                    }

                    //数量的处理
                    backData.detailList.forEach(element => {
                        if (backData.businessType > 95 || backData.businessType < 100) {
                            //退货
                            element.baseQuantity = Math.abs(element.baseQuantity) - (element.cumRetQuantity ? element.cumRetQuantity : 0);
                        } else {
                            //其他
                            element.baseQuantity = Math.abs(element.baseQuantity) - (element.cumExecuteQuantity ? element.cumExecuteQuantity : 0);
                        }
                        element.orgBaseQuantity = element.baseQuantity;
                    });

                        //如果数量为0,则删除该条数据
                        // let generateData = [];
                        // backData.detailList.forEach(element => {
                        //     if(element.baseQuantity != 0){
                        //         generateData.push(element)
                        //     }
                        // });

                        backData.detailList = backData.detailList.filter(item => item.baseQuantity != 0);

                        //console.log('生单的详情数据', backData);
                        //需要弹窗分单的单据
                        if (source == 'PurchaseOrder' || source == 'PurchaseReceiveVoucher' || source == 'PurchaseReturn' || source == 'ProductReceiveVoucher' || source == 'DelegateReceiveVoucher' || source == 'ProductionOrder' || source == 'SaleDelivery') {
                            if (Object.keys(backData).length > 0) {
                                // 分单列表 查询条件
                                let fenDanpostData = {
                                    dataSource: 'PuArrival',
                                    businessType: 2, //1:退货业务 2：非退货业务 3: 退货 + 非退货 4: 发票
                                    someBusinessType: '0',    // 指定业务类型 默认 0
                                    startVoucherState: 0,
                                    endVoucherState: 10
                                };
                                switch (source) {
                                    case 'PurchaseOrder':
                                        //采购订单 到 采购到货单
                                        fenDanpostData.dataSource = null;
                                        this.$refs.purchaseOrderRef.purchaseShowModel(fenDanpostData);
                                        break;
                                    case 'SaleDelivery':
                                        //销售发货单
                                        // this.$router.push({ path: '/sale/saleDelivery' })
                                        fenDanpostData.dataSource = null;
                                        this.$refs.saleRef.purchaseShowModel(fenDanpostData);
                                        break;
                                    case 'PurchaseReceiveVoucher':
                                        //采购到货 -> 采购入库单
                                        this.$refs.purchaseInRef.purchaseShowModel(fenDanpostData);
                                        break;
                                    case 'PurchaseReturn':
                                        //采购退货 -> 采购入库单
                                        fenDanpostData.someBusinessType = '99';
                                        this.$refs.purchaseInRef.purchaseShowModel(fenDanpostData);
                                        break;
                                    case 'ProductReceiveVoucher':
                                        //产成品入库单 || 完工入库单
                                        fenDanpostData.dataSource = null;
                                        this.$refs.productionInRef.purchaseShowModel(fenDanpostData);
                                        break;
                                    case 'DelegateReceiveVoucher':
                                        //委外入库
                                        // this.$router.push({ path: '/outsource/outWarehouseIn' })
                                        //委外到货 -> 委外入库单
                                        fenDanpostData.dataSource = "DelegateArrival";
                                        this.$refs.delegateInRef.purchaseShowModel(fenDanpostData);
                                        break;
                                    case 'ProductionOrder':
                                        //生产订单
                                        // this.$router.push({ path: '/production/management/productionOrder' });
                                        fenDanpostData.dataSource = null;
                                        this.$refs.productionOrderRef.purchaseShowModel(fenDanpostData);
                                        break;
                                    default:
                                        this.$message.error('生单失败');
                                        break;
                                }
                            }
                        } else {
                            if (this.templateDetails.length > 0) {
                                //console.log(this.templateDetailsMain)
                                //如果是生成凭证模板 把凭证模板 数据带上
                                this.$set(backData, 'templateDetailsMain', this.templateDetailsMain)
                            }
                            if(n==0||n==1||n==2){
                                let nbackData = backData;
                                nbackData.detailList = arr;
                                if(this.$route.path == '/production/productionPlan' && (n == 0 || n == 1 || n == 2)){
                                    nbackData.detailList.forEach(element=>{
                                        element.sourceVoucherType = "主生产计划",
                                        //element.sourceVoucherType = "MasterProductionSchedule",
                                        element.sourceVoucherCode = nbackData.voucherCode
                                    })
                                }
                                if(this.$route.path == '/production/management/productionOrder' && (n == 0 || n == 1 || n == 2)){
                                    nbackData.detailList.forEach(element=>{
                                        element.sourceVoucherType = "物料需求计划",
                                        //element.sourceVoucherType = "RequirementPlan",
                                        element.sourceVoucherCode = nbackData.voucherCode
                                    })
                                }
                                this.$store.commit('SET_ARR', nbackData)
                                //console.log(backData);
                            }else{
                                this.$store.commit('SET_ARR', backData)
                            }

                            // 如果$store.state.order.invoiceData有数据，才能生单
                            if (Object.keys(this.invoiceData).length > 0) {
                                //console.log(Object.keys(this.invoiceData),'Object.keys(this.invoiceData)')
                                switch (source) {
                                    case 'PuArrival':
                                        //采购到货单
                                        this.$router.push({ path: '/procurement/purchaseReceipt' })
                                        break;
                                    case 'ReleaseProduction':
                                        //生产订单---新增liulang
                                        this.$router.push({ path: '/production/productionWork' })
                                        break;
                                    case 'AssignOutsourcing':
                                        //下达委外---新增liulang
                                        this.$router.push({ path: '/outsource/outProductionWork' })
                                        break;
                                    case 'ReleaseProcurement':
                                        //下达采购---新增liulang
                                        this.$router.push({ path: '/procurement/purchaseRequisition' })
                                        break;
                                    case 1:
                                        //采购退货单(未入库退货)
                                        this.$router.push({ path: '/procurement/purchaseReturn' })
                                        break;
                                    case "purchaseReturn":
                                        //采购退货单(已入库退货)
                                        this.$router.push({ path: '/inventory/bills/purchaseReturn' })
                                        break;
                                    case 'PurchaseInvoice':
                                        //采购发票
                                        this.$router.push({ path: '/procurement/purchaseInvoice' })
                                        break;
                                    case 'SaleQuotation':
                                        //报价单
                                        this.$router.push({ path: '/sale/saleQuotation' })
                                        break;
                                    case 'SaleOrder':
                                        //销售订单
                                        this.$router.push({ path: '/sale/saleOrder' })
                                        break;
                                    case 2:
                                        if (this.$route.path == '/inventory/bills/saleDelivery') {
                                            //退货通知单(库存管理)
                                            this.$router.push({ path: '/inventory/bills/saleReturn' })
                                        } else {
                                            //退货通知单
                                            this.$router.push({ path: '/sale/saleReturn' })
                                        }
                                        break;
                                    case 'SaleInvoice':
                                        //销售发票
                                        this.$router.push({ path: '/sale/saleInvoice' })
                                        break;
                                    case 'SaleDispatchVoucher_1':
                                        if (this.$route.path == '/inventory/bills/saleDelivery') {
                                            //销售出库单(库存管理)
                                            this.$router.push({ path: '/inventory/bills/saleOut' })
                                        } else {
                                            //销售出库单
                                            this.$router.push({ path: '/sale/saleOut' })
                                        }
                                        break;
                                    case 'OtherReceiveVoucher':
                                        //其他入库单
                                        this.$router.push({ path: '/inventory/bills/otherIn' })
                                        break;
                                    case 'SaleDispatchVoucher':
                                        //出库业务--销售出库单
                                        this.$router.push({ path: '/inventory/bills/saleOut' })
                                        break;
                                    case 'DelegateInvoice':
                                        //委外发票
                                        this.$router.push({ path: '/outsource/outInvoice' })
                                        break;
                                    case 'MaterialDispatchVoucher':
                                        //材料出库单
                                        this.$router.push({ path: '/inventory/bills/materialOut' })
                                        // this.$refs.meterialOutRef.purchaseShowModel(1);
                                        break;
                                    case 'MaterialDispatchVoucherBack':
                                        //材料退料单
                                        this.$router.push({ path: '/inventory/bills/materialOutRet' })
                                        break;
                                    case 'DelegateDispatchVoucher':
                                        //委外出库
                                        this.$router.push({ path: '/inventory/bills/delegateOut' })
                                        break;
                                    case 'DelegateDispatchVoucherBack':
                                        //委外退料单
                                        this.$router.push({ path: '/inventory/bills/delegateOutRet' })
                                        break;
                                    case 'DelegateRRS':
                                        //委外领料单
                                        this.$router.push({ path: '/outsource/outPicking' })
                                        break;
                                    case 'OtherDispatchVoucher':
                                        //其他出库单
                                        this.$router.push({ path: '/inventory/bills/otherOut' })
                                        break;
                                    case 'ProductionWork':
                                        //加工单
                                        this.$router.push({ path: '/production/productionWork' })
                                        break;
                                    case 'ProductionPlan':
                                        //生产计划
                                        this.$router.push({ path: '/production/productionPlan' })
                                        break;
                                    case 'productionDemand':
                                        //生产运算
                                        this.$router.push({ path: '/production/productionDemand' })
                                        break;
                                    case 'ReceivableVoucher':
                                        //应收单
                                        this.$router.push({ path: '/finance/receiveManagement/receivableVoucher' });
                                        break;
                                    case 'PayableVoucher':
                                        //应付单
                                        this.$router.push({ path: '/finance/paymentManagement/payableVoucher' });
                                        break;
                                    case 'PayOtherVoucher':
                                        //其他应付单
                                        this.$router.push({ path: '/finance/paymentManagement/payOtherVoucher' });
                                        break;
                                    case 'Contract':
                                        //合同签订
                                        this.$router.push({ path: '/contract/contractBills' });
                                        break;
                                    case 'Credentials':
                                        //凭证
                                        this.$router.push({ path: '/finance/accounting/credentials' });
                                        break;
                                    default:
                                        this.$message.error('生单失败');
                                        break;
                                }
                            }


                        }
                } else {
                    // this.$message.warning(res.message);
                }
            })

        },
        //=============================== 生单 ==========================



        /**
        * 处理动态表单数据
        * @example handleDynamicData('请求参数')
        */
        handleDynamicData(code) {
            listDesign({ source: code }).then((response) => {
                if (response.code === 200) {
                    const { data } = response;

                    //给动态表名新增value字段（用于提交数据）
                    for (let i = 0; i < data.length; i++) {
                        const element = data[i];
                        element.value = '';
                        element.valueId = '';
                        element.valueName = '';
                    }


                    this.dynamicFormData = data.filter(item => item.onOff == true);  //返回的详细数据
                    //console.log(this.dynamicFormData)
                } else {
                    // this.$message.warning(res.message);
                }
            })
        },
        //重组表格columns
        regroupTableColumns(datas) {
            let tableColumns = [];
            let data = _.cloneDeep(datas);
            data.unshift({
                name: '序号',
                code: 'number',
                key: 'number',
                columnWidth: 40,
                // fixed: 'left',
                align: 'center',
            })

            //面积计算表出入库情况 塞入 出库数量 入库数量
            if (this.areaInOut) {
                data.splice(2, 0, {
                    code: "inNum",
                    columnType: "小数",
                    name: '入库数量',
                    dataType: 1,
                    onEdit: true,
                    onFill: true,
                    onOff: true,
                    value: '',
                    valueName: '',
                    columnWidth: 100,
                });
                data.splice(3, 0, {
                    code: "outNum",
                    columnType: "小数",
                    name: '出库数量',
                    dataType: 1,
                    onEdit: true,
                    onFill: true,
                    onOff: true,
                    value: '',
                    valueName: '',
                    columnWidth: 100,
                });
            }



            if (data && typeof data == 'object') {
                //采购管理（采购入库单）隐藏仓库和仓库编码
                if (this.isHideWherehouse) {
                    // data = data.filter(item => item.code != 'warehouseName')
                    // data = data.filter(item => item.code != 'warehouseCode')inventoryName
                    data = data.filter(item => item.code != 'warehouseCode')
                    data = data.filter(item => item.name != '仓库')
                }

                //采购到货，采购退货  隐藏明细中的客户
                if (this.isDetailCrmId) {
                    data = data.filter(item => item.code != 'crmId')
                }

                //采购订单  隐藏明细中的供应商
                if (this.isDetailVendorId) {
                    data = data.filter(item => item.code != 'vendorId')
                }


                //质检单 隐藏明细中的工序字段
                if (this.isDetailRecord) {
                    data = data.filter(item => item.code != 'procedureId')
                }





                for (let i = 0; i < data.length; i++) {
                    if (data[i].columnType == '搜索选择') {
                        data[i].code = IdFieldToNameField(data[i].code)
                    }

                    let title = data[i].name;
                    if (data[i].onFill) {
                        title = <div><span style="color:red;font-family: SimSun,sans-serif;font-size:14px">*</span> {data[i].name}</div>
                    }

                    if (this.isAreaX) {
                        //面积计算表 title不处理必填
                        title = data[i].name;
                    }



                    let columns = {
                        title: title,
                        key: data[i].code,
                        dataIndex: data[i].code,
                        scopedSlots: { customRender: data[i].code },
                        width: data[i].columnWidth,
                        fixed: data[i].fixed,
                        align: data[i].align,
                        ellipsis: true,
                    }
                    tableColumns.push(columns)
                }
                //console.log('表头columns:', tableColumns)
            } else {
                this.$message.error('error');
                return;
            }
            return tableColumns;
        },
        compareDate(date1, date2) {
            //时间比较大小
            var oDate1 = new Date(date1);
            var oDate2 = new Date(date2);
            if (oDate1.getTime() >= oDate2.getTime()) {
                return true; //第一个大
            } else {
                return false; //第二个大
            }
        },
        /**
         * 组装提交数据
         * data:{
         *  detail:明细
         *  header:表头
         *  footer:表尾
         *  customField：自定义字段
         *  /^(\d+[a-zA-Z]+|[a-zA-Z]+\d+)([0-9a-zA-Z]*)$/ 包含数字或者字母的code，就是自定义数据
         * }
         */
        submitRegData(data) {

            let commitData = {
                orderDetailList: [],//请购单明细
                defineFields: '',//自定义字段
            };

            //保存要提交的合计字段
            data.detail.forEach(item => {
                if (item.name == 'total') {
                    commitData.totalQuantity = item.baseQuantity;//数量
                    commitData.totalAmount = item.amount;//金额
                    commitData.totalTaxAmount = item.tax;//税额
                    commitData.totalIncludeTaxAmount = item.includeTaxAmount;//含税金额
                }
            });


            let m = data.detail.slice(0, -1);//删除合计列

            let reg = /^(\d+[a-zA-Z]+|[a-zA-Z]+\d+)([0-9a-zA-Z]*)$/;//（自定义字段）必须包含字母和数字


            let s = [];//传给后台的明细表数据
            if (this.sourceCode != 'ProcedurePrice') {
                for (let i = 0; i < m.length; i++) {
                    if (m[i].inventoryId || m[i].inventoryCode || m[i].inventoryName || m[i].no) {//有物料id或者物料名字的才传给后台  m[i].no//（新西亚）产品名称
                        s.push(m[i])
                    } else if (this.financeType) {//财务除外，都可以传给后台
                        if (m[i].amount || m[i].amount == 0) {
                            s.push(m[i])
                        } else if (m[i].baseQuantity || m[i].no) {
                            s.push(m[i])
                        }
                    }
                }
            } else {
                s = m;
            }

            //明细表自定义数据
            for (const key in s) {
                let cust = {};
                for (const k in s[key]) {
                    if (reg.test(k)) {
                        let a = {};
                        a[k] = s[key][k];
                        Object.assign(cust, a)
                    }
                }
                s[key].defineFields = JSON.stringify(cust);
            }

            commitData.orderDetailList = Object.assign([], s);

            commitData.defineFields = JSON.stringify(this.regroupSubmitData(data.customField));

            return commitData = Object.assign(
                commitData,
                this.regroupSubmitData(data.header),
                this.regroupSubmitData(data.footer)
            )
        },
        //提交数据时 获取数据的value值
        regroupSubmitData(data) {
            let m = {};
            //console.log("regroupSubmitData", data);
            //不可修改的也要传值给后台的处理
            let array = ['procedureFlag', 'businessType', 'purchaseTypeCode', 'warehouseCode', 'crmId', 'crmName', 'productCode', 'inventorySpecification', 'planDirection', 'contractPrice', 'projectCode', 'projectNo', 'inventoryDescript'];
            let checkArray = (code) => {
                return array.includes(code);
            }
            for (const key in data) {
                if (data[key].onEdit === true || checkArray(data[key].code)) {
                    if (data[key].valueId) {
                        //如果valueId存在，说明要提交的是选中的id
                        m[data[key].code] = data[key].valueId;
                    } else {
                        m[data[key].code] = data[key].value;
                    }
                }
            }
            //console.log("regroupSubmitData转换之后:", m);
            return m;
        },
        //判断是否是数组
        isArray(obj) {
            return Object.prototype.toString.call(obj) === '[object Array]';
        },
        //是否是对象
        isObject(obj) {
            return Object.prototype.toString.call(obj) === '[object Object]';
        },
        // deepCopy (target) {
        //     // 定义一个变量
        //     let result;
        //     //如果当前需要深拷贝的是一个对象的话
        //     if (typeof target === 'object') {
        //         //如果是一个数组的话
        //         if (Array.isArray(target)) {
        //             result = []; // 将result赋值为一个数组，并且执行遍历
        //             for (let i in target) {
        //                 //递归克隆数组中的每一项
        //                 result.push(this.deepCopy(target[i]));
        //             }
        //             // 判断如果当前的值是null的话；直接赋值为null
        //         } else if (target === null) {
        //             result = null;
        //             // 判断如果当前的值是一个RegExp对象的话，直接赋值
        //         } else if (target.constructor === RegExp) {
        //             result = target;
        //         } else {
        //             // 否则是普通对象，直接for in循环，递归赋值对象的所有值
        //             result = {};
        //             for (let i in target) {
        //                 result[i] = this.deepCopy(target[i]);
        //             }
        //         }
        //         // 如果不是对象的话，就是基本数据类型，那么直接赋值
        //     } else {
        //         result = target;
        //     }
        //     // 返回最终结果
        //     return result;
        // },
        //下拉选择赋值处理
        handleDownChoice(id, val) {
            let label = '';
            val = JSON.parse(val);
            val.forEach(element => {
                if (id == element.key) {
                    label = element.label;
                }
            });
            return label;
        },
        //处理下拉选择（退货单情况）
        formatSelectJsonVal(val) {
            let thisVal = JSON.parse(val);
            let backVal = [];
            if (thisVal && thisVal != '' && thisVal != null) {
                thisVal.forEach((item, index) => {
                    //采购退货||销售退货 （因为页面单独分出来，单独判断）
                    // if (this.businessType) {
                    //     if ((item.key == 99 || item.key == 98 || item.key == 97 || item.key == 96) && this.businessType == 1) {
                    //         backVal.push(item);
                    //     }
                    //     if (item.key != 99 && item.key != 98 && item.key != 97 && item.key != 96 && this.businessType != 1) {
                    //         backVal.push(item);
                    //     }
                    // } else {
                    //其他单据处理   业务类型
                    backVal.push(item);
                    // }

                });
            }
            return backVal;
        },
        //列表和单据切换
        switchList(type) {
            this.showModel = type;
            //order
            console.log(type);
            if (type == 'list') {
                //列表
                if (this.routePath != '/contract/contractBillsRecord') { //合同变更记录列表 不是动态的 所以不需要调用 动态列表组件
                    this.$refs.dyList.searchList();
                    this.$refs.dyList.getMyselfPlan();
                    //重新获取动态字段
                    this.$refs.dyList.handleDynamicData();
                }
            } else if (type == 'detail') {
                //明细
                this.$refs.detailSearchRef.getSystemplan();
                this.$refs.detailSearchRef.getMyselfPlan();
                this.$refs.detailSearchRef.getUnit();
            } else if (type == 'statistical') {
                //统计
                this.$refs.statisticalSearchRef.getSystemplan();
                this.$refs.statisticalSearchRef.getMyselfPlan();
                this.$refs.statisticalSearchRef.getUnit();
            }
        },
        //刷新
        syncOrder() {
            this.initForm(2);
            if (this.routePath != '/contract/contractBillsChange') {//合同变更页面不需要获取最新一条数据（它根据id获取指定数据）
                //console.log('当前单据id:', this.orderId, this.$route.query.id);
                if (this.$route.query.id) {
                    this.orderId = this.$route.query.id;
                }
                if(this.routePath == '/production/management/productionOrder' && this.$route.query.numbers == 4){
                    //this.$store.commit('SET_MRP', [])
                } else{
                    this.getIdByData();
                }
                //this.getIdByData(); //获取最新一条数据
                //console.log('获取最新一条数据,当前单据id:', this.orderId, this.$route.query.id);
            }

            if (this.sourceCode == 'Contract') {
                this.initDetails = true;
                //合同签订 多个明细标签页  刷新跳转到合同标的
                this.activeKeyContract = 1;
            }
        },
        //按钮的权限控制
        btnPermission(behind) {
            let parameter = {
                path: this.$route.path,//当前页面路径
                behind: behind,//权限后半段标识
                permissionAll: this.permissions,//当前用户所有的权限标识
            }
            return btnpermiss.btnPermission(parameter);
        },
        //统计表和明细表的搜索
        searchClick(type) {
            if (type == 'detail') {
                this.$refs.detailSearchRef.searchDynamic();
            }
            if (type == 'statistical') {
                this.$refs.statisticalSearchRef.searchDynamic();
            }
        },
        //根据仓库 获取现存量
        async getNowQuantityFun(inventoryIds, warehouseId, isWherehouse) {
            let request = {
                inventoryIds: inventoryIds,
                warehouseId: warehouseId
            }
            await getNowQuantity(request).then(res => {
                if (res.code === 200) {
                    this.existingQuantityBack = res.data;

                    this.dataSource.forEach(item => {
                        if (isWherehouse) {
                            item.existingQuantity = null;
                        }
                        for (const key in res.data) {
                            if (item.inventoryId == key) {
                                item.existingQuantity = res.data[key];
                            }
                        }
                    });
                    this.reload();
                }
            })
        },

        //单据提交
        submitOrder(type) {
            let data = {
                id: this.orderId,
                status: type,//状态 -1:撤回提交,0:提交
            }
            //console.log(this.orderId);
            if (!this.orderId) {
                this.$message.warning('该单据未保存不需要提交');
                return;
            }
            if (this.voucherState == -1 && type == -1) {
                this.$message.warning('该单据未提交无需撤回提交');
                return;
            }
            submitOrder(data).then(res => {
                if (res.code === 200) {
                    if (type == 0) {
                        this.$message.success('提交成功');
                    } else {
                        this.$message.success('撤回提交成功');
                    }
                    this.getIdByData();
                }
            })
        },
        //==========================================财务======================================
        verificationFun() {
            //财务核销
            if (this.sourceCode == 'ReceivableVoucher') {
                //应收核销
                this.$router.push(`/finance/receiveManagement/receiveVerification?orderId=${this.orderId}`);//跳转到核销页面
            } else if (this.sourceCode == 'PayableVoucher') {
                //应付核销
                this.$router.push(`/finance/paymentManagement/payVerification?orderId=${this.orderId}`);//跳转到核销页面
            }

        },
        forceRerender() {
            // 刷新往来单位 组件
            this.refreshSearch = false;
            this.$nextTick(() => {
                this.refreshSearch = true;
            });
        },
        //往来类型改变
        downSelectChange(value) {
            //console.log('往来类型改变:', value)
            //console.log('当前数据', this.orderHeaderData, this.orderFooterData)
            this.orderHeaderData.forEach(item => {
                // supplie      供应商
                // office       部门
                // employees    业务员、请购人、检验
                // crm  //客户
                if (item.code == 'partnerId') {
                    this.refreshSearch = false;
                    if (value == 1) {//供应商
                        item.val = 'supplie';
                    } else if (value == 2) {//客户
                        item.val = 'crm';
                    } else if (value == 3) {//员工
                        item.val = 'employees';
                    } else if (value == 4) {//部门
                        item.val = 'office';
                    } else {
                        item.val = 'contacts';//往来单位
                    }
                    setTimeout(() => {
                        this.refreshSearch = true;
                    }, 200)
                }
                if (item.code == 'businessType') {
                    this.businessType = value;
                }
            });
        },
        //导出
        exportDetail() {
            //统计表 明细表 导出
            if (this.showModel == 'detail') {
                //明细
                this.$refs.detailSearchRef.export(this.voucherTitle);
            } else if (this.showModel == 'statistical') {
                //统计
                this.$refs.statisticalSearchRef.export(this.voucherTitle);
            }
        },

        //财务  获取凭证模板
        getTemplateFinance() {
            let data = {
                current: 1,
                size: -1,
                voucherType: this.sourceCode,
            }
            getList(data).then(res => {
                if (res.code === 200) {
                    res.data.records.forEach(item => {
                        item.key = item.id;
                    });
                    this.templateFinanceData = res.data.records;//凭证模板列表
                }
            })
        },
        templateShow() {
            //选择凭证模板
            this.templateVisible = true;
            this.getTemplateFinance();
        },
        templateCancel() {
            this.templateVisible = false;
            this.templateFinanceData = [];
            this.selectedTemplateKeys = [];
            this.selectedTemplateRows = [];
            this.templateDetails = [];
            this.templateDetailsMain = [];
        },
        templateOk() {
            if (this.selectedTemplateKeys.length != 1) {
                this.$message.warning('请选择一条凭证模板');
                return;
            } else {
                //生成凭证
                this.templateVisible = false;
                this.templateFinanceData = [];
                this.selectedTemplateKeys = [];
                this.selectedTemplateRows = [];
                setTimeout(() => {
                    this.generateBills('Credentials');
                }, 400)
            }
        },
        onSelectTemplateChange(keys, rows) {
            this.selectedTemplateKeys = keys;
            this.selectedTemplateRows = rows;
            this.getTemplateDetail();
        },
        getTemplateDetail() {
            //获取模板详情
            detail({ id: this.selectedTemplateKeys[0] }).then(res => {
                this.templateDetailsMain = res.data;
                this.templateDetails = res.data.voucherTemplateDetailList;
            })
        },
        //出入库 确认
        theGoods(type) {
            //type 1:入库 2：出库 3：退货入库
            //console.log(type)
            let _this = this;
            _this.inOutType = type;
            let requestData = {
                id: _this.orderId,
                isCheckInventoryInfo: true
            }
            confirm(requestData).then((response) => {
                if (response.code === 5002) {
                    this.inOutMessage = response.message;
                    response.message = JSON.parse(response.message);
                    //console.log(response.message.length);
                    // return

                    if (response.message.length > 0) {
                        MiddleUtils.$emit("OpenInOutWarning", response.message, _this.submitInOutYes);
                    } else {
                        let content = '';
                        if (type == 1) {
                            content = '是否确认入库？'
                        } else if (type == 2) {
                            content = '是否确认出库？'
                        } else if (type == 3) {
                            content = '是否确认退货入库？'
                        }
                        this.$confirm({
                            title: "提示",
                            content: (
                                <span style="color:red">{content}</span>
                            ),
                            onOk() {
                                _this.submitInOutYes()
                            },
                            onCancel() { },
                        });
                    }


                } else {
                    // _this.$message.warning(response.message);
                }
            })
        },
        //确认 出入库
        submitInOutYes() {
            let _this = this;
            let requestData = {
                id: _this.orderId,
                isCheckInventoryInfo: false
            }
            confirm(requestData).then((response) => {
                if (response.code === 200) {
                    if (_this.inOutType == 1) {
                        _this.$message.success('入库成功');
                    } else if (_this.inOutType == 2) {
                        _this.$message.success('出库成功');
                    } else if (_this.inOutType == 3) {
                        _this.$message.success('退货入库成功');
                    }
                    _this.getIdByData();
                    MiddleUtils.$emit("HideInOutWarning");
                } else {
                    // _this.$message.warning(response.message);
                }
            })
        },

    },
}


/**
 * 单据请求code汇总：
 */

// PurchaseRequisition	请购单
// PurchaseOrder	    采购订单
// PuArrival	        到货单
// PurchaseInvoice	    采购发票


// SaleQuotation	    报价单
// SaleOrder	        销售订单
// SaleDelivery	        销售发货单
// SaleInvoice	        销售发票


// PurchaseReceiveVoucher	采购入库单
// ProductReceiveVoucher	产成品入库单
// DelegateReceiveVoucher   委外入库
// OtherReceiveVoucher	    其他入库单


// SaleDispatchVoucher	    销售出库单
// MaterialDispatchVoucher	材料出库单
// DelegateDispatchVoucher  委外发料
// OtherDispatchVoucher	    其他出库单
// StockRequestVoucher	    领料单

// ReceiveVoucher	收款单
// PaymentVoucher	付款单

// ReceivableVoucher	应收款单
// PayableVoucher	    应付款单
// OtherReceivableVoucher	其他应收款单
// OtherPayableVoucher	    其他应付款单


// OutSourceExpenseVoucher	委外费用单
// OutSourceOrder	        委外加工单
// PraVoucher	            采购需求分析
// PurchaseArrivalPeriodStart	期初进货单
// CostAllocationOrder	    产品成本分配单
// AdjustCostInVoucher	    入库调整单
// AdjustCostOutVoucher	出库调整单
// TransVoucher	调拨单
// CheckVoucher	盘点单
// ShareExpenseVoucher	        费用分摊单
// PurchaseSettleVoucher	    采购核算单
// PSPurchaseReceiveVoucher	    期初暂估入库单
// PSSaleDispatchVoucher	    期初销售出库单
// RedBackVoucher	    红字回冲单
// BlueBackVoucher	    蓝字回冲单
